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

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. 

主站蜘蛛池模板: 莱州市| 永清县| 元朗区| 九台市| 和平区| 红原县| 滨海县| 独山县| 乌兰浩特市| 南安市| 西昌市| 含山县| 修武县| 伊吾县| 长子县| 南阳市| 普安县| 田东县| 宁夏| 汉中市| 张家口市| 潢川县| 从化市| 琼海市| 浪卡子县| 乳源| 西贡区| 安国市| 玉屏| 陇南市| 惠水县| 水城县| 昌黎县| 阳曲县| 惠水县| 新郑市| 绥滨县| 琼中| 都江堰市| 桂平市| 左权县|