In Go's http package, how do I get the query string on a POST request?

前端 未结 6 608
滥情空心
滥情空心 2021-01-30 03:59

I\'m using the httppackage from Go to deal with POST request. How can I access and parse the content of the query string from the Requestobject ? I can

6条回答
  •  情深已故
    2021-01-30 04:23

    Here's a more concrete example of how to access GET parameters. The Request object has a method that parses them out for you called Query:

    Assuming a request URL like http://host:port/something?param1=b

    func newHandler(w http.ResponseWriter, r *http.Request) {
      fmt.Println("GET params were:", r.URL.Query())
    
      // if only one expected
      param1 := r.URL.Query().Get("param1")
      if param1 != "" {
        // ... process it, will be the first (only) if multiple were given
        // note: if they pass in like ?param1=¶m2= param1 will also be "" :|
      }
    
      // if multiples possible, or to process empty values like param1 in
      // ?param1=¶m2=something
      param1s := r.URL.Query()["param1"]
      if len(param1s) > 0 {
        // ... process them ... or you could just iterate over them without a check
        // this way you can also tell if they passed in the parameter as the empty string
        // it will be an element of the array that is the empty string
      }    
    }
    

    Also note "the keys in a Values map [i.e. Query() return value] are case-sensitive."

提交回复
热议问题