Go HandlerFunc()
How to use http.HandlerFunc in Go to convert regular functions into HTTP handlers and register them with http.Handle.
This program demonstrates Go’s http.HandlerFunc type adapter. The http.HandlerFunc function converts a regular function with the (http.ResponseWriter, *http.Request) signature into a type that satisfies the http.Handler interface, allowing it to be passed to http.Handle. This is useful when you want to use the Handle method instead of HandleFunc.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main
import (
"io"
"net/http"
)
func dogs(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "This is the web about dogs!\n")
}
func cats(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "This is the web about cats!\n")
}
func main() {
http.Handle("/dogs/", http.HandlerFunc(dogs))
http.Handle("/cats", http.HandlerFunc(cats))
http.ListenAndServe(":8080", nil)
}
This post is licensed under CC BY 4.0 by the author.