Go implements HTTP server and parses header parameters and form parameters
In the http service, header parameters and form parameters are frequently used. This article mainly describes how to parse parameters and form parameters in the Http request header in the Go language, the 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 ("listener failed:", err. Error ())
}
}
Func helloFunc (w http. ResponseWriter, r * http. Request ){
Fmt. Println ("Print Header parameter list :")
If len (r. Header)> 0 {
For k, v: = range r. Header {
Fmt. Printf ("% s = % s \ n", k, v [0])
}
}
Fmt. Println ("printed 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 username and password. If the password succeeds, the session is returned in the header. If the password fails, the StatusUnauthorized status code is returned.
W. WriteHeader (http. StatusOK)
If (r. Form. Get ("user") = "admin") & (r. Form. Get ("pass") = "888 "){
W. Write ([] byte ("hello, Verification Successful! "))
} Else {
W. Write ([] byte ("hello, Verification Failed! "))
}
}
After running, run the following request in the chrom Browser: http: // 127.0.0.1: 8001/hello? User = admin & pass = 888. The server prints the following parameter list:
Print the 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
Print the Form parameter list:
User = admin
Passes = 888
The successful result is returned to the client, and the running result in the browser is:
If the browser does not contain the/hello request, 404 is returned. If the parameter is set to another one, the verification failure result is returned!
This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151166.htm