// Created on savesnippets.com ยท https://savesnippets.com/9hIzdUv13YVVCD package main import ( "encoding/json" "log" "net/http" ) type CreateUserRequest struct { Name string `json:"name"` Email string `json:"email"` } type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` } func createUser(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } var req CreateUserRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "bad json: "+err.Error(), http.StatusBadRequest) return } user := User{ID: 42, Name: req.Name, Email: req.Email} w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(user) } func main() { http.HandleFunc("/users", createUser) log.Fatal(http.ListenAndServe(":8080", nil)) }