当前位置:网站首页>Go receives get / post parameters and sends get / post requests

Go receives get / post parameters and sends get / post requests

2020-12-06 08:51:52 osc_ z3ivsxnp

Golang: receive GET and POST Parameters

GET and POST They are the two most commonly used requests , Let's talk about how to use the golang In service , Correctly receive the parameter information of these two requests .


Handle GET request


1.1 receive GET request

// receive GET request 
func Get(writer http.ResponseWriter , request *http.Request) {
   
   

    query := request.URL.Query()

    //  The first way 
    // id := query["id"][0]

    //  The second way 

    id := query.Get("id")

    log.Printf("GET: id=%s\n", id)

    fmt.Fprintf(writer, `{"code":0}`)
}



func main(){
   
   

    http.HandleFunc("/get", Get)
    log.Println("Running at port 9999 ...")
    err := http.ListenAndServe(":9999", nil)
    if err != nil {
   
   
        log.Fatal("ListenAndServe: ", err.Error())
    }

}

Postman launch get request
 Insert picture description here

Rerun program , request Postman, The server console is printed as follows :

2020/12/04 11:33:55 Running at port 9999 ...
2020/12/04 11:34:09 GET: id=123

1.2 receive GET request

func Get(writer http.ResponseWriter , request *http.Request) {
   
    

    result := make(map[string]string)
    keys := request.URL.Query()
    for k, v := range keys {
   
    
        result[k] = v[0]
    }
    log.Println(result)
}

func main(){
   
    

    http.HandleFunc("/get", Get)
    log.Println("Running at port 9999 ...")
    err := http.ListenAndServe(":9999", nil)
    if err != nil {
   
    
        log.Fatal("ListenAndServe: ", err.Error())
    }

}

Rerun program , request Postman, The server console is printed as follows :

2020/12/04 12:37:17 Running at port 9999 ...
2020/12/04 12:37:21 map[id:123 name:sina]

It should be noted that , there req.URL.Query() It's an array , because go You can receive id=1&id=2 This form of parameter and put it in the same key Next



receive POST request

In development , frequently-used POST There are two kinds of requests , Namely application/json and application/x-www-form-urlencoded, Here are two types of processing methods .

1.1 receive application/x-www-form-urlencoded Type of POST request

func handlePostForm(writer http.ResponseWriter, request *http.Request) {
   
      
    request.ParseForm()

    //  The first way 
    // username := request.Form["username"][0]
    // password := request.Form["password"][0]

    //  The second way 
    username := request.Form.Get("username")
    password := request.Form.Get("password")
    
    fmt.Printf("POST form-urlencoded: username=%s, password=%s\n", username, password)
    
    fmt.Fprintf(writer, `{"code":0}`)
}

func main(){
   
      

    http.HandleFunc("/handlePostForm", handlePostForm)
    log.Println("Running at port 9999 ...")
    err := http.ListenAndServe(":9999", nil)
    if err != nil {
   
      
        log.Fatal("ListenAndServe: ", err.Error())
    }

}

Postman launch x-www-form-urlencoded request
 Insert picture description here

Rerun program , request Postman, The server console is printed as follows :

2020/12/04 12:44:32 Running at port 9999 ...
POST form-urlencoded: username= Li Si , password=12


1.2 receive application/x-www-form-urlencoded Type of POST request

func PostForm(w http.ResponseWriter, r *http.Request) {
   
        

    var result = make(map[string]string)
    r.ParseForm()
    for k,v := range r.PostForm {
   
        
       if len(v) < 1 {
   
          continue  }
       result[k] = v[0]
    }

    log.Println(result)

}

func main(){
   
        

    http.HandleFunc("/PostForm", PostForm)
    log.Println("Running at port 9999 ...")
    err := http.ListenAndServe(":9999", nil)
    if err != nil {
   
        
        log.Fatal("ListenAndServe: ", err.Error())
    }

}

Rerun program , request Postman, The server console is printed as follows :

2020/12/04 12:49:40 Running at port 9999 ...
2020/12/04 12:49:45 map[password:12 username: Li Si ]


2 Handle application/json request

In development , It's often data objects , We need to put these data objects into JSON Form return of , Now let's add a piece of code :

JSON structure
such as , Requested the interface of the mobile phone's home location ,json The following data is returned :

{
   
          
    "resultcode": "200",
    "reason": "Return Successd!",
    "result": {
   
          
        "province": " Zhejiang ",
        "city": " Hangzhou ",
        "areacode": "0571",
        "zip": "310000",
        "company": " China Mobile ",
        "card": ""
    }
}

This is the idea :

1. First the json Turn into struct.

2. then json.Unmarshal() that will do .

json turn struct , It's too much trouble to write by yourself , There are many online tools that you can use directly , I used this :

https://mholt.github.io/json-to-go/

Put... On the left json And then it comes out struct 了 .

Use code to realize :

//AutoGenerated  Structure 
type AutoGenerated struct {
   
           
        Resultcode string `json:"resultcode"`
        Reason     string `json:"reason"`
        Result     struct {
   
           
                Province string `json:"province"`
                City     string `json:"city"`
                Areacode string `json:"areacode"`
                Zip      string `json:"zip"`
                Company  string `json:"company"`
                Card     string `json:"card"`
        } `json:"result"`
}
func PostJson(w http.ResponseWriter, r *http.Request ) {
   
           

    body ,err := ioutil.ReadAll(r.Body)
    if  err != nil {
   
           
       log.Println( err)
    }
    log.Printf("%s",body)

    var data AutoGenerated
    json.Unmarshal([]byte(body),&data)

    //Json Structure returns 
    json,_ := json.Marshal(data)
    w.Write(json)

}

func main(){
   
           

    http.HandleFunc("/PostJson", PostJson)
    log.Println("Running at port 9999 ...")
    err := http.ListenAndServe(":9999", nil)
    if err != nil {
   
           
        log.Fatal("ListenAndServe: ", err.Error())
    }

}

Postman launch application/json request
 Insert picture description here

Rerun program , Access page , The server console is printed as follows :

2020/12/04 12:57:01 {
   
           
    "resultcode": "200",
    "reason": "Return Successd!",
    "a":"dd",
    "result": {
   
           
        "province": " Zhejiang ",
        "city": " Hangzhou ",
        "areacode": "0571",
        "zip": "310000",
        "company": " China Mobile ",
        "card": "33"
    }
}

Welcome to reprint , Reprint please indicate the source .









版权声明
本文为[osc_ z3ivsxnp]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/202012060851321844.html