Dynamic Routes in Go #

Build a Go web server without external dependencies — just the standard library.

In this short example, you’ll create a basic web server and handle dynamic routes. We’ll use http.NewServeMux() for routing. By the end, you'll have a working server with dynamic routes you can build on.

Like a name tag #

When you arrive somewhere new, you usually don’t know anyone’s name. That’s why you get a blank name tag and write your name on it.

Same name tag, different names.

It’s the same with dynamic routes in Go. You define one endpoint, and when the server is running, people can enter their names and get different responses.

Setup a dynamic route #

From the previous tutorial, we learned about the /{$} route pattern. This time, we’ll make use of it again but replace the $ with an identifier: name. This lets us put any name after /tag/, and we can access this value using r.PathValue("name").

Example

mux.HandleFunc("GET /tag/{name}", func(w http.ResponseWriter, r *http.Request) {
	name := r.PathValue("name")
	fmt.Fprintf(w, "Hello, %s", name)
})

The /tag/{name} route pattern matches any pattern such as /tag/alice or /tag/bob.

Complete Example #


package main

import (
	"errors"
	"fmt"
	"net/http"
	"os"
)

func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("GET /tag/{name}", func(w http.ResponseWriter, r *http.Request) {
		name := r.PathValue("name")
		fmt.Fprintf(w, "Hello, %s", name)
	})

	srv := &http.Server{
		Addr:    fmt.Sprintf(":%d", 8080),
		Handler: mux,
	}

	err := srv.ListenAndServe()
	if !errors.Is(err, http.ErrServerClosed) {
		os.Exit(1)
	}
}
Simple Web Server that demonstrates dynamic routes in Go.

Try It with curl #

Once your server is running, you can test it using:

curl http://localhost:8080/tag/alice

You should see this response:

Hello, alice!

Contributions

Special thanks to Patrick Henry Winston his book Make It Clear was instrumental in shaping this article. Looking ahead, I’ll be focusing on two projects: Beago, a Go framework for building LLM-powered applications, and Vona, a minimalist and lightweight starter kit that that utilises Pico for beautiful plug-and-play landing page UI blocks.

Read more