How to properly handle JSON POST request in Go?
Hello everyone! I just started learning Go and am writing a simple REST API server. I encountered a problem with JSON processing in POST requests.\n\nI have a User struct:\n\n```go\ntype User struct {\n Name string\n Age int\n}\n```\n\nAnd a handler:\n\n```go\nfunc createUser(w http.ResponseWriter, r *http.Request) {\n if r.Method != http.MethodPost {\n http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)\n return\n }\n\n var user User\n err := json.NewDecoder(r.Body).Decode(&user)\n if err != nil {\n http.Error(w, err.Error(), http.StatusBadRequest)\n return\n }\n\n fmt.Fprintf(w, "User: %+v", user)\n}\n```\n\nWhen I send a POST request via curl:\n```\ncurl -X POST -H "Content-Type: application/json" -d '{"name":"John","age":30}' http:
No answers yet.
Log in to leave an answer
Blogs