How to Read Request Body and Query Parameters in Go

Web
Read query parameters with r.URL.Query() and parse the request body using json.NewDecoder(r.Body) in Go.

Use r.URL.Query() for query parameters and json.NewDecoder(r.Body) for JSON request bodies in your HTTP handler.

func handler(w http.ResponseWriter, r *http.Request) {
    // Query parameters
    id := r.URL.Query().Get("id")
    
    // Request body (JSON)
    var data struct {
        Name string `json:"name"`
    }
    if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    fmt.Fprintf(w, "ID: %s, Name: %s", id, data.Name)
}