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?
How about this?
req.ParseForm()
req.Form.Get(key)
did you already test it with req.PostFormValue
instead of req.FormValue
?
I've found solution with calling ParseMultipartForm
before ParseForm
, it works for me.
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.
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!
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>")
// 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
Try this buddy.
hope it will work as it works for me
r.FormValue("userid")