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

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. 

主站蜘蛛池模板: 乐平市| 石渠县| 阿巴嘎旗| 吴江市| 新化县| 岑溪市| 镇远县| 志丹县| 阳东县| 博湖县| 年辖:市辖区| 连云港市| 类乌齐县| 治多县| 垦利县| 游戏| 正定县| 黔南| 安宁市| 延吉市| 科尔| 泸定县| 黔西| 锡林浩特市| 定州市| 静宁县| 桑植县| 泗阳县| 横峰县| 天柱县| 沙雅县| 新河县| 佛学| 卢龙县| 东辽县| 辽阳县| 贞丰县| 仁布县| 寻甸| 玛曲县| 平利县|