In HTTP service, header parameters and form parameters are often used. This article is mainly to practice how to parse the parameters and form parameters in the header of HTTP request in Go language. The specific code is as follows:
package server import ( "net/http" "strconv" "fmt" ) func HttpStart(port int) { http.HandleFunc("/hello", helloFunc) err := http.ListenAndServe(":"+strconv.Itoa(port), nil) if err != nil { fmt.Println("Listening failed:",err.Error()) } } func helloFunc(w http.ResponseWriter, r *http.Request) { fmt.Println("Printing Header Parameter list:") if len(r.Header) > 0 { for k,v := range r.Header { fmt.Printf("%s=%s\n", k, v[0]) } } fmt.Println("Printing Form Parameter list:") r.ParseForm() if len(r.Form) > 0 { for k,v := range r.Form { fmt.Printf("%s=%s\n", k, v[0]) } } //Verify the user name and password. If it succeeds, session will be returned in the header. If it fails, status unauthorized status code will be returned w.WriteHeader(http.StatusOK) if (r.Form.Get("user") == "admin") && (r.Form.Get("pass") == "888") { w.Write([]byte("hello,Verification succeeded!")) } else { w.Write([]byte("hello,Verification failed!")) } }
After running, execute the request in the Chrome browser: http: / / 127.0.0.1:8001 / Hello? User = Admin & pass = 888. The server will print the parameter list as follows:
Printing Header Parameter list:
Accept-Language=zh-CN,zh;q=0.9
Connection=keep-alive
Cache-Control=max-age=0
Upgrade-Insecure-Requests=1
User-Agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.19 Safari/537.36
Accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding=gzip, deflate, br
//To print a list of Form parameters:
user=admin
pass=888
And the successful result will be returned to the client. The running result in the browser is:
If the browser does not request / hello, it will report 404. If other parameters are written, it will also return the result of validation failure!