In the HTTP service, header parameters and form parameters are often used, this article is mainly to practice in the go language, how to parse the HTTP request header parameters and form parameters, the following code:
Package Serverimport ( "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 ("Print Form parameter list:") r.parseform () If Len (r.form) > 0 {for k,v: = Range R.form { fmt. Printf ("%s=%s\n", K, v[0] } } //Verifies the username password, if successful the header returns to the session, and the failure returns the Statusunauthorized status code W. Writeheader (http. Statusok) if (R.form.get ("user") = = "Admin") && (R.form.get ("pass") = = "888") { w.write ([]byte] (" Hello, verify success! ") })} else { w.write ([]byte (" Hello, validation failed! ")) }}
After running, execute the request in Chrom Browser: http://127.0.0.1:8001/hello?user=admin&pass=888, the server will print the parameter list as follows:
Print header parameter list: Accept-language=zh-cnZh; q=0.9Connection=keep-alivecache-control=max-age=0Upgrade-insecure-requests=1User-agent=mozilla/5.0(Windows NT10.0; WOW64) AppleWebKit/537.36(khtml, like Gecko) Chrome/65.0.3325.19 Safari/537.36Accept=text/html, application/xhtml+xml, application/xml; q=0.9,image/webp,image/apng,*/*;q=0.8accept- Encoding=gzip, deflate< Span class= "Prism-token prism-punctuation", br print form parameter list: User=adminpass =888
And will return the successful result to the client, the result of running in the browser is:
If the browser is not requested/hello will be reported 404, if the parameter write other will also return the result of validation failure!
Implement HTTP server in Golang and parse header parameters and form parameters