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
Syntax
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
Parameters
| Parameter | Description |
|---|---|
"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
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.
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
| Version | Change |
|---|---|
| Go 1.22 | Added |
Related
context.WithTimeout and WithCancel· Derive a context that is cancelled after a timeout or on demand, to stop work and outbound calls that take too long.encoding/json Marshal and Unmarshal· Convert Go values to JSON and back using struct tags to name fields, omit empty values and skip fields.- Go HTTP Server · tutorial