golang http server,can't get post value

2019-04-19 10:04发布

func login(rw http.ResponseWriter, req *http.Request) {
    req.ParseForm()

    if req.Method == "GET" {
        fmt.Fprintf(rw, "Error Method")
    } else {
        name := strings.TrimSpace(req.FormValue("userid"))
        fmt.Println("userid:", name)
        fmt.Println("pwd:", req.FormValue("pwd"))
        fmt.Fprintf(rw, "welcome back,%s", req.FormValue("userid"))
    }
}

and i using ASIhttprequst send a from,like this.

[self setRequest:[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://127.0.0.1:8080/login"]]];
[request setPostValue:@"userid" forKey:@"fdfs@jkjlf.cm"];
[request setPostValue:@"pwd" forKey:@"fdsfdsfdkskfjhds"];
[request setRequestMethod:@"POST"];

i got a null value with req.FormValue("userid")

what happend? and how to fix it?

标签: http go
8条回答
聊天终结者
2楼-- · 2019-04-19 10:13

How about this?

req.ParseForm()
req.Form.Get(key)
查看更多
女痞
3楼-- · 2019-04-19 10:14

I've found solution with calling ParseMultipartForm before ParseForm, it works for me.

查看更多
做自己的国王
4楼-- · 2019-04-19 10:17

To extract a value from a post request you have to call r.ParseForm() at first. This parses the raw query from the URL and updates r.Form.

For POST or PUT requests, it also parses the request body as a form and put the results into both r.PostForm and r.Form. POST and PUT body parameters take precedence over URL query string values in r.Form.

Now your r.From is a map of all values your client provided. To extract a particular value you can use r.FormValue("<your param name>") or r.Form.Get("<your param name>").

So basically you will have this:

r.ParseForm()
res := r.FormValue("<your param name>")
查看更多
再贱就再见
5楼-- · 2019-04-19 10:18

If you make multipart/form-data POST request, ParseForm does not parse request body correctly (this might be a bug). So, use ParseMultipartForm if that is the case.

Or you can call FormValue or PostFormValue directly without calling these parse methods.

查看更多
劳资没心,怎么记你
6楼-- · 2019-04-19 10:23

I had similar issues using ParseForm. I ended up doing something like this:

type UserRequest struct {
  UserId  string `json:"userid"`
  Pwd     string `json:"pwd"`
}

func login(w http.ResponseWriter, r *http.Request) {
   var ur UserRequest
   decode := json.NewDecoder(r.Body)
   decoder.Decode(&ur)

   // Access data via struct
}

Hope that helps!

查看更多
贪生不怕死
7楼-- · 2019-04-19 10:23
    // Form contains the parsed form data, including both the URL
    // field's query parameters and the POST or PUT form data.
    // **This field is only available after ParseForm is called.**
    // The HTTP client ignores Form and uses Body instead.
    Form url.Values

    // PostForm contains the parsed form data from POST, PATCH,
    // or PUT body parameters.
    //
    // **This field is only available after ParseForm is called.**
    // The HTTP client ignores PostForm and uses Body instead.
    PostForm url.Values
查看更多
登录 后发表回答