Home>Article>Backend Development> How to use golang http
It is said that the go standard library is practical and the API design is simple. This time, I will use the net/http package in the go standard library to implement a simple http web server, including three versions.
The simplest version(Recommended learning:go)
Use directly
http.HandleFunc(partern,function(http.ResponseWriter,*http.Request){})
HandleFunc accepts two parameters, the first is the routing address, and the second is the processing method.
//v1 func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("httpserver v1")) }) http.HandleFunc("/bye", sayBye) log.Println("Starting v1 server ...") log.Fatal(http.ListenAndServe(":1210", nil)) } func sayBye(w http.ResponseWriter, r *http.Request) { w.Write([]byte("bye bye ,this is v1 httpServer")) }
Customized Handler
Looking at the standard library source code, the v1 version actually calls the handle method. The incoming HandlerFunc implements the Handler's ServeHTTP method. In fact, It is ServeHTTP that is doing http request processing.
## From this we can customize our own Handler, the code is as follows:
// v2 func main() { mux := http.NewServeMux() mux.Handle("/", &myHandler{}) mux.HandleFunc("/bye", sayBye) log.Println("Starting v2 httpserver") log.Fatal(http.ListenAndServe(":1210", mux)) } type myHandler struct{} func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte("this is version 2")) } func sayBye(w http.ResponseWriter, r *http.Request) { w.Write([]byte("bye bye ,this is v2 httpServer")) }
Customized server configuration
I dealt with Handler once before, let’s take a look at the secrets in http.ListenAndServe().It turns out that you can customize the http server configuration here, which is all in the Server structure. This object can configure the listening address port and configure the read and write timeout. time, configure the handler, configure the maximum number of bytes of the request header..., all of which are slightly modified from the previous program to get the current program:
// v3 func main() { mux := http.NewServeMux() mux.Handle("/", &myHandler{}) mux.HandleFunc("/bye", sayBye) server := &http.Server{ Addr: ":1210", WriteTimeout: time.Second * 3, //设置3秒的写超时 Handler: mux, } log.Println("Starting v3 httpserver") log.Fatal(server.ListenAndServe()) } type myHandler struct{} func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte("this is version 3")) } func sayBye(w http.ResponseWriter, r *http.Request) { // 睡眠4秒 上面配置了3秒写超时,所以访问 “/bye“路由会出现没有响应的现象 time.Sleep(4 * time.Second) w.Write([]byte("bye bye ,this is v3 httpServer")) }
The above is the detailed content of How to use golang http. For more information, please follow other related articles on the PHP Chinese website!