Your cart is currently empty!
Golang: HTTP Server
Go
x
2
1
// Signature
2
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
Go
1
14
14
1
func main() {
2
3
http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
4
5
// Method #1
6
w.Write([]byte("hello from w.Write"))
7
// Method #2
8
io.WriteString(w, "hello from io.WriteString")
9
// Method #3
10
fmt.Fprintf(w, "hello from fmt.Fprintf")
11
})
12
13
http.ListenAndServe(":8080", nil)
14
}
To test, you can run:
Shell
1
1
1
curl localhost:8080/ping
It should response one of the three methods (or all three).
UPDATE:
Before Golang version 1.22, you only can define “path” as the first argument of http.HandleFunc.
But, starting from Golang version 1.22 the pattern becomes:
1
1
1
[METHOD ][HOST]/[PATH]
Please check here for more information about the new pattern https://pkg.go.dev/net/http#hdr-Patterns.
References:
Leave a Reply