官术网_书友最值得收藏!

Breaking down the code

We just updated the empty files in one single go and started running the server. Let me now explain each and every piece of the file main.go:

  • Imported a few packages. github.com/narenaryan/romanNumerals is the data service we created before.
  • net/http is the core package we used to handle an HTTP request through its HandleFunc function. That function's arguments are http.Request and http.ResponseWriter. Those two deal with the request and response of an HTTP request.
  • r.URL.Path is the URL path of the HTTP request. For the CURL Request one, it is /roman_number/5. We are splitting this path and using the second argument as a resource and the third argument as a value to get the Roman numeral. The Split function is in a core package called strings.
  • The Atoi function converts an alphanumeric string to an integer. For the numerals map to consume, we need to convert the integer string to an integer. The Atoi function comes from a core package called strconv.
  •  We use http.StatusXXX to set the status code of the response header. The WriteHeader and Write functions are available on the response object for writing the header and body, respectively.
  • Next, we created an HTTP server using &http while initializing a few parameters like address, port, timeout, and so on.
  • The time package is used to define seconds in the program. It says, after 10 seconds of inactivity, automatically return a 408 request timeout back to the client.
  • EscapeString escapes special characters to become valid HTML characters. For example, Fran & Freddie's becomes Fran & Freddie's&#34.
  • Finally, start the server with the  ListenAndServe function. It keeps your web server running until you kill it.

One should write unit tests for their API. In the upcoming chapters, we will see how to test an API end to end. 

主站蜘蛛池模板: 涟水县| 上高县| 盱眙县| 富裕县| 铜川市| 斗六市| 阿拉善右旗| 徐闻县| 惠水县| 康乐县| 蓬安县| 蓝山县| 江陵县| 徐州市| 静海县| 金秀| 汉中市| 庄浪县| 南丹县| 津市市| 德兴市| 耿马| 兴国县| 沁阳市| 芜湖市| 横峰县| 万荣县| 得荣县| 三门峡市| 博乐市| 松阳县| 阜新市| 宜州市| 嘉荫县| 凤凰县| 德州市| 乐业县| 逊克县| 湖北省| 隆安县| 黄冈市|