Router

The router maps incoming HTTP requests to specific handlers.

While many frameworks provide routing features, Go has it built-in.

Create a file named main.go with the following content:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello!")
	})

	if err := http.ListenAndServe(":3000", nil); err != nil {
		panic(err)
	}
}

To run the server, execute:

$ go run main.go

You can test the server with:

$ curl localhost:3000
Hello!

Variable in Path

To handle variables in the path, you can modify the router like this:

http.HandleFunc("/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello %s!", r.PathValue("name"))
})

You can now test this with:

$ curl localhost:3000/hello/go
Hello go!