Home > Backend Development > Golang > How to use golang http

How to use golang http

(*-*)浩
Release: 2019-12-03 10:43:24
Original
3033 people have browsed it

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){})
Copy after login

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"))
}
Copy after login

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.

How to use golang http

How to use golang http

How to use golang http

## 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"))
}
Copy after login

Customized server configuration

I dealt with Handler once before, let’s take a look at the secrets in http.ListenAndServe().

How to use golang http

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"))
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template