Implementing Http server in Golang and parsing header parameters and form parameters

Keywords: Go xml Session Windows encoding

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 (

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:")
   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
   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: / / / Hello? User = Admin & pass = 888. The server will print the parameter list as follows:

Printing Header Parameter list:
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-Encoding=gzip, deflate, br
//To print a list of Form parameters:

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!

Posted by KCAstroTech on Wed, 01 Apr 2020 05:54:39 -0700