Go
http.HandleFunc
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())
Exercise 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.
Show example 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)
}
Test yourself
-
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
Show answer
It returns 405 Method Not Allowed — The Go 1.22 ServeMux automatically returns 405 with an Allow header when the path matches but the method doesn't.
-
Register a route
mux := http.NewServeMux()
mux.____("GET /saglik", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
Show answer
mux := http.NewServeMux()
mux.HandleFunc("GET /saglik", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
-
Pattern and matching path
- "GET /urunler"
- Only GET /urunler
- "/statik/"
- Everything under /statik/
- "GET /urunler/{id}"
- /urunler/7
- "/"
- All unmatched paths
Next lesson: JSON API