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

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. 

主站蜘蛛池模板: 芷江| 城步| 马关县| 洛宁县| 灵璧县| 泾川县| 炉霍县| 桐乡市| 渭南市| 阿巴嘎旗| 达日县| 鄂伦春自治旗| 榕江县| 论坛| 芜湖县| 宁津县| 锡林浩特市| 达日县| 商都县| 梁山县| 天等县| 靖远县| 肇东市| 桂东县| 奇台县| 林西县| 绥滨县| 虹口区| 土默特左旗| 灯塔市| 东安县| 灵宝市| 北宁市| 轮台县| 宾阳县| 沧州市| 新龙县| 兴国县| 屏南县| 玉屏| 临邑县|