Standard library / net/http
http.NewServeMux()
Creates an independent HTTP router. Method and wildcard patterns require Go 1.22 routing semantics. Expected stdout: '42\n'.
Formal Syntax & Structure
go syntaxgo
func NewServeMux() *ServeMuxReturn Value
*ServeMux
Operation result; check errors and validity indicators when returned.
Working Example
Example Snippetgo
package main
import ( "bytes" "fmt" "io" "mime/multipart" "net" "net/http" "net/http/httptest" "strings" "time")
func main() { m := http.NewServeMux() m.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, r.PathValue("id")) }) fmt.Println(rec(m, "GET", "/items/42").Body.String())}func rec(h http.Handler, method, path string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, nil)) return w}func fixture() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }))}func localServer() (*http.Server, string, chan error) { l := must(net.Listen("tcp4", "127.0.0.1:0")) s := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }), ReadHeaderTimeout: time.Second} done := make(chan error, 1) go func() { done <- s.Serve(l) }() return s, "http://" + l.Addr().String(), done}func form() *http.Request { r := httptest.NewRequest("POST", "/?q=query", strings.NewReader("q=body&name=Go")) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") return r}func multipartReq() *http.Request { var b bytes.Buffer w := multipart.NewWriter(&b) f := must(w.CreateFormFile("upload", "demo.txt")) _, e := io.WriteString(f, "hello") check(e) check(w.Close()) r := httptest.NewRequest("POST", "/", &b) r.Header.Set("Content-Type", w.FormDataContentType()) return r}
func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}