Parsing Request

Accessing Query Parameters

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/query", func(w http.ResponseWriter, r *http.Request) {
		query := r.URL.Query()
		fmt.Fprintf(w, "foo: %s\n", query.Get("foo"))
		fmt.Fprintf(w, "all: %+v", query["foo"])
	})
	if err := http.ListenAndServe(":3000", nil); err != nil {
		panic(err)
	}
}
$ curl 'localhost:3000/query?foo=2&foo=3'                                                                                                                                                                                                                                                                                                        <<<
foo: 2
all: [2 3]

Parsing Request Body

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	http.HandleFunc("POST /person", func(w http.ResponseWriter, r *http.Request) {
		var p Person
		json.NewDecoder(r.Body).Decode(&p)
		fmt.Fprintf(w, "Person: %+v", p)
	})

	if err := http.ListenAndServe(":3000", nil); err != nil {
		panic(err)
	}
}
$ curl localhost:3000/person -id '{"age": 7, "name": "Alice"}'
HTTP/1.1 200 OK
Date: Sat, 26 Oct 2024 05:24:47 GMT
Content-Length: 26
Content-Type: text/plain; charset=utf-8

Person: {Name:Alice Age:7}