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

Understanding Go's net/http package

Accepting HTTP requests is the primary goal of a web server. In Go, there is a system-level package that helps developers create HTTP servers and clients. The name of the package is net/http. We can understand the functionality of the net/http package by creating a small example. The example accepts an incoming request and returns the timestamp of the server. Let us see the steps for creating such a server:

  1. Create the program file as follows:
touch -p $GOPATH/src/github.com/git-user/chapter2/healthCheck/main.go

Now, we have a file where we can develop a server with a Health Check API that returns a date/time string.

  1. Import the net/http package and create a function handler called HealthCheck. The http.HandleFunc is a method that takes a route and a function handler as its arguments. This function handler has to return an http.ResponseWriter object:
package main

import (
"io"
"log"
"net/http"
"time"
)

// HealthCheck API returns date time to client
func HealthCheck(w http.ResponseWriter, req *http.Request) {
currentTime := time.Now()
io.WriteString(w, currentTime.String())
}

func main() {
http.HandleFunc("/health", HealthCheck)
log.Fatal(http.ListenAndServe(":8000", nil))
}

The preceding code creates a HealthCheck function and attaches it to an HTTP route. HandleFunc is used to attach a route pattern to a handler function. ListenAndServe starts a new HTTP server. It returns an error if the server launch is unsuccessful. It takes address:port as the first argument and the second argument is nil, which says use the default multiplexer. We will see multiplexers in detail in the upcoming sections.

Use the log function to debug potential errors. The  ListenAndServe function returns an error if there is one.
  1. Now, we can start the web server using this command:
go run $GOPATH/src/github.com/git-user/chapter2/healthCheck/main.go

Run the healthCheck.go file from a shell.

  1. Now, fire up a shell or browser to see the server in action. Here, we use the curl request:
curl -X GET http://localhost:8000/health

The response is as follows:

2019-04-10 17:54:05.450783 +0200 CEST m=+6.612810181

Go has a different concept for handling request and response. We used the io library to write to the response. For web development, we can use a template to automatically fill in the details. Go's internal URL handlers use a ServeMux multiplexer. In the next section, we will discuss more on ServeMux, a built-in URL router in Go.

主站蜘蛛池模板: 太仆寺旗| 云浮市| 井陉县| 绥阳县| 米泉市| 古丈县| 卫辉市| 高邑县| 都兰县| 泰和县| 华池县| 徐州市| 海口市| 东港市| 水城县| 万全县| 昌邑市| 湄潭县| 繁峙县| 明星| 扬州市| 山东省| 东阿县| 溧水县| 定兴县| 阿坝| 永宁县| 芦山县| 儋州市| 兖州市| 綦江县| 宁国市| 莱州市| 乌拉特前旗| 开远市| 宣恩县| 日照市| 新巴尔虎左旗| 龙南县| 秦皇岛市| 定结县|