golang http server,can't get post value

2019-04-19 09:53发布

问题:

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?

回答1:

How about this?

req.ParseForm()
req.Form.Get(key)


回答2:

did you already test it with req.PostFormValue instead of req.FormValue ?



回答3:

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



回答4:

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.



回答5:

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!



回答6:

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>")


回答7:

    // 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


回答8:

Try this buddy.

hope it will work as it works for me

r.FormValue("userid")


标签: http go