package main import ( "fmt" "net/http" "github.com/julienschmidt/httprouter" ) func main() { router := httprouter.New() router.POST("/users", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { username := r.FormValue("username") password := r.FormValue("password") fmt.Fprintf(w, "Hello %s! Your password is %s.", username, password) }) http.ListenAndServe(":8080", router) }
package main import ( "encoding/json" "net/http" "github.com/julienschmidt/httprouter" ) type User struct { Username string `json:"username"` Password string `json:"password"` } func main() { router := httprouter.New() router.POST("/users", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { decoder := json.NewDecoder(r.Body) var user User err := decoder.Decode(&user) if err != nil { http.Error(w, "Invalid request body", http.StatusBadRequest) return } // do something with the user object... w.WriteHeader(http.StatusCreated) }) http.ListenAndServe(":8080", router) }This example shows how to use the POST method to handle requests that contain JSON data. We use the `encoding/json` package to decode the JSON data into a User struct, and then perform some action with the user. If the JSON data is invalid, we return an error response with a `400 Bad Request` status code. Overall, the httprouter Router POST package provides a simple and efficient way to handle HTTP POST requests in your golang web applications.