http.HandleFunc
- Go course
- Intermediate
- Lesson 68/80
- 4 min
Learn to map a path with HandleFunc.
http.HandleFunc and ServeMux
http.ServeMux routes an incoming request to the right handler by path. Since Go 1.22, patterns can include a method and path variables:
mux := http.NewServeMux()
mux.HandleFunc("GET /urunler", liste)
mux.HandleFunc("POST /urunler", ekle)
mux.HandleFunc("GET /urunler/{id}", getir)
mux.Handle("/statik/", http.StripPrefix("/statik/", http.FileServer(http.Dir("web"))))
http.ListenAndServe(":8080", mux)A pattern ending in / also catches subpaths; the most specific (longest) pattern wins.
Server settings
http.ListenAndServe has no timeouts; slow clients can hold connections forever. In production an http.Server is configured:
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
log.Fatal(srv.ListenAndServe())Practice Routes
Add the route "GET /merhaba/{ad}" to a ServeMux; it writes "Merhaba " + r.PathValue("ad"). Send GET and POST requests for /merhaba/Ada; print the GET body and the POST status code.
Starter code
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /merhaba/{ad}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Merhaba "+r.PathValue("ad"))
})
get := httptest.NewRecorder()
mux.ServeHTTP(get, httptest.NewRequest("GET", "/merhaba/Ada", nil))
post := httptest.NewRecorder()
mux.ServeHTTP(post, httptest.NewRequest("POST", "/merhaba/Ada", nil))
fmt.Println(get.Body.String())
fmt.Println(post.Code)
}Expected output
Merhaba Ada 405
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If a <code>POST</code> request hits the <code>"GET /urunler"</code> pattern, what happens?
- The handler still runs
- It returns 404
- The server crashes
- It returns 405 Method Not Allowed Correct answer
Explanation: The Go 1.22 ServeMux automatically returns 405 with an Allow header when the path matches but the method doesn't.
2 Register a route
mux := http.NewServeMux()
mux.____("GET /saglik", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
mux := http.NewServeMux()
mux.HandleFunc("GET /saglik", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
Explanation: HandleFunc registers a function as the handler for a pattern.
3 Pattern and matching path
| Term | Meaning |
|---|---|
"GET /urunler" |
Only GET /urunler |
"/statik/" |
Everything under /statik/ |
"GET /urunler/{id}" |
/urunler/7 |
"/" |
All unmatched paths |