Go 1.27 reference · Files, HTTP and Logging

Go http.ServeMux and HandleFunc Type

Route HTTP requests by method and path pattern (with {wildcards}) to handler functions using the standard library.

Go 1.27 Since 1.22

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))

Parameters

ParameterDescription
"GET /items/{id}" Method plus path with a wildcard.
r.PathValue("id") Read a wildcard.
"/files/{path...}" Match the rest of the path.
"/{$}" Only the exact root path.

Examples

Example 1
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "item %s", r.PathValue("id"))
	})
	for _, req := range []*http.Request{
		httptest.NewRequest("GET", "/items/42", nil),
		httptest.NewRequest("DELETE", "/items/42", nil),
	} {
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, req)
		fmt.Println(req.Method, rec.Code, rec.Body.String())
	}
}

Output

GET 200 item 42
DELETE 405 Method Not Allowed

Run this on your computer — see “Get Started” for setup.

An HTTP client call with a timeout
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"time"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, `{"status":"ok"}`)
	}))
	defer srv.Close()
	client := &http.Client{Timeout: 2 * time.Second}
	resp, err := client.Get(srv.URL)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type"), string(body))
}

Output

200 application/json {"status":"ok"}

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Go 1.22Added

Was this page helpful?