Golang: HTTP Server

// Signature
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
func main() {

	http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {

		// Method #1
		w.Write([]byte("hello from w.Write"))
		// Method #2
		io.WriteString(w, "hello from io.WriteString")
		// Method #3
		fmt.Fprintf(w, "hello from fmt.Fprintf")
	})

	http.ListenAndServe(":8080", nil)
}

To test, you can run:

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:

[METHOD ][HOST]/[PATH]

Please check here for more information about the new pattern https://pkg.go.dev/net/http#hdr-Patterns.

References:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *