Simple Web Server with Routes #
Build a Go web server without external dependencies — just the standard library.
Learn how to write simple, efficient web applications using Go. The time you invest in mastering the basics of Go’s standard library will yield greater returns than nearly any other technical investment you make.
In this short section, you'll create a basic web server using only the
net/http package. We'll handle routing with
http.NewServeMux(). By the end, you'll have a working server
you can build on.
You don't need any external dependencies to build a production-ready web server in Go.
Changing Tires #
Imagine you're changing your car's wheels from winter to summer. You only need two tools:
- A jack to lift the car
- A wrench to loosen the bolts
- (And of course, new tires)
You don't need a mechanic or a shop and you don't have to pay anyone.
It's the same with Go. The standard library is stable, fast, and all you need to build lightweight and reliable web servers.
Import the Package #
Here's the only import required to get started:
import "net/http"
Set Up a Router #
First, we create a new http.NewServeMux. It's a request
multiplexer that matches incoming requests to registered handlers based on
the request path.
We can now register routes on the mux using
HandleFunc. This function takes two arguments:
- The method and route path (e.g.
"GET /") -
A handler function that matches this signature:
func(http.ResponseWriter, *http.Request)
Example
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
})
The /{$} route pattern matches only the / route
and does not match paths like /foo, /bar or
/foo/bar.
Complete Example #
package main
import (
"errors"
"fmt"
"net/http"
"os"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
srv := &http.Server{
Addr: fmt.Sprintf(":%d", 8080),
Handler: mux,
}
err := srv.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
os.Exit(1)
}
}
Try It with curl #
Once your server is running, you can test it using:
You should see this response:
Hello, World!
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.