How do you build a Web service with Golang? The go Web programming tutorial on cainiao’s official website has already introduced how the Web server works, so I won’t go into details here. Let’s start with an example: http.go

package main import ( "fmt" "io" "log" "net/http" ) func main() { http.HandleFunc("/test", DoRequest) // Set access route err := http.ListenAndServe(":8000", nil) // Set listening port if err! = nil { log.Fatal("ListenAndServe: ", err)}} func doRequest(w http.responsewriter, r * http.request) {r.parseForm (); For POST, the body of the response package is parsed (request body) // fmt.println (r.foo) // fmt.println ("path", r.URL.Path) //fmt.Println("scheme", r.URL.Scheme) //for k, v := range r.Form { // fmt.Println("key:", k) // fmt.Println("value:", strings.Join(v, "")) //} fmt.Fprintf(w, "service start..." // If the ParseForm method is not called, write to the client using the IO.WriteString object. //query := r.ul.query () var uid string // Initialize the definition variable if r.thod == "GET" {uid = r.fowler ("uid")} else if  r.Method == "POST" { uid = r.PostFormValue("uid") } io.WriteString(w, "uid = "+uid) }Copy the code

Go run http.go Runs the program. After enter the address in your browser: http://127.0.0.1:8000/test? Uid =10086, look at the result.

In the main function, we call an http.HandleFucn function from the NET/HTTP package to register a handler that takes two arguments. The first one is a string, and this is the route matching, so I’m going to do the /test route. The second argument is a ResponseWriter (Request) signature. Our doRequest function is such a signature. ListenAndServe(“:8000”, nil) in the next line, ListenAndServe(“:8000”, nil) means listen on port 8000 of localhost, ignore nil for now.

In the doRequest function we have two arguments, one of type http.ResponseWriter. It is like a response flow and is actually an interface type.

The second is the http.Request type, which is similar to an HTTP Request. We don’t have to use all the parameters, if it’s just a simple output, then we’ll just use http.responseWriter, io.writeString, which will write the output stream to the data.

Let’s change it a little bit. Please pay attention to the changes.

func main() { mux := http.NewServeMux() mux.HandleFunc("/test", doRequest) err := http.ListenAndServe(":8000", Mux) // Set the listening port if err! = nil { log.Fatal("ListenAndServe: ", err) } }Copy the code

In this example, we no longer use nil in the function HTTP.ListenAndServe. This example is actually the same as the previous example. ServeMux is used to register hanlder function patterns using HTTP. Let’s adjust to a more complicated example:

package main import ( "fmt" "io" "log" "net/http" ) var mux map[string]func(http.ResponseWriter, *http.Request) func main() { server := http.Server{ Addr: ":8000", Handler: &doHandler{}, } mux = make(map[string]func(http.ResponseWriter, *http.Request)) mux["/test"] = doRequest err := server.ListenAndServe() if err ! = nil { log.Fatal("ListenAndServe: ", err) } } type doHandler struct{} func (*doHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if res, ok := mux[r.URL.String()]; ok { res(w, r) return } io.WriteString(w, "url params: "+ r.ul.string ())} func doRequest(w http.responsewriter, r * http.request) {r.parseForm (); FMT.Fprintf(w, "service start...") // This is written to the client using the following IO.WriteString object}Copy the code

For this example, instead of defining ServeMux, we use http.server. Both run the server with the NET/HTTP package.