Reputation: 854
I have the following Go program which I want to read the JSON values send from via post. I have tried few different methods example r.Body = http.MaxBytesReader(w, r.Body, 1048576)
first then only run Json.NewDecoder(r.Body).Decode(&u)
. All methods seems to be giving the same EOF error. I have even tried this body, err := ioutil.ReadAll(r.Body)
. So all seem the same
func insertUser(w http.ResponseWriter, r *http.Request) {
type User struct {
Uemail string `json:"uEmail"`
Upass string `json:"uPass"`
}
var u User
if r.Method == "POST" {
if r.Header.Get("Content-Type") != "" {
value, _ := header.ParseValueAndParams(r.Header, "Content-Type")
if value != "application/json" {
msg := "Content-Type header is not application/json"
json.NewEncoder(w).Encode(Errormessage{msg});
return
}
}
//r.Body = http.MaxBytesReader(w, r.Body, 1048576)
/*body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}*/
err := json.NewDecoder(r.Body).Decode(&u)
if err != nil {
fmt.Println("Decoding error is :", err)
json.NewEncoder(w).Encode(Errormessage{"Message decoding Issue"});
return
}
var uEmail string = u.Uemail
var uPass string = u.Upass
fmt.Println("User Namess :", uEmail)
fmt.Println("User Password :", uPass)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
}
Upvotes: 1
Views: 7769
Reputation: 1238
Please try running the following
func insertUser(w http.ResponseWriter, r *http.Request) {
type User struct {
Uemail string `json:"uEmail"`
Upass string `json:"uPass"`
}
var u User
if r.Method == "POST" {
if r.Header.Get("Content-Type") != "" {
value, _ := header.ParseValueAndParams(r.Header, "Content-Type")
if value != "application/json" {
msg := "Content-Type header is not application/json"
json.NewEncoder(w).Encode(Errormessage{msg});
return
}
}
// CODE CHANGED HERE
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
// handle error
return
}
err = json.Unmarshal(body, &u)
if err != nil {
// handle error
return
}
// CHANGED TILL HERE
var uEmail string = u.Uemail
var uPass string = u.Upass
fmt.Println("User Namess :", uEmail)
fmt.Println("User Password :", uPass)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
}
}
Upvotes: 0