I programmed multiple methods for my handler which look like this for example:
func DeleteProduct(w http.ResponseWriter, r *http.Request){
log.Println(r.Form)
db.Exec("Delete from products where Id = "+r.FormValue("Id"))
}
The problem is that r.Form is always an empty map, in my delete request I send the Id in a JSON which looks like this:
{
"CustomerDate": "13.03.2018",
"CustomerDateTime": "13:30",
"UserId": 4
}
in the main method I register the handler methods like this:
router.HandleFunc("/delete",handler.DeleteProduct).Methods("DELETE")
Why is the r.Form and the r.PostForm always an empty map?
In case of JSON request you have to unmarshal
request body before using any parameter.
For example:
type ReqBody struct {
CustomerDateTime string `json:"CustomerDateTime"`
CustomerDateTime string `json:"CustomerDateTime"`
UserId int `json:"UserId"`
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
// Error handler...
}
rb := ReqBody{}
json.Unmarshal(body, &rb)
// Now you can perform something like this:
println(rb.UserId)