Go Playbook

Course › Week 5 · HTTP services with net/http › Day 1 · lesson 29 of 42 · 15 min reading + 60 min practice

Routing and handlers

An http.ServeMux with methods and path parameters in its patterns, and handlers.

net/httpServeMuxHandlerFuncPathValue

On this page
  1. A server
  2. Routes
  3. Coming from PHP
  4. Practice
  5. Remember

A Laravel app needs PHP-FPM and nginx in front of it to answer HTTP. A Go program is the server: net/http in the standard library listens on a port, parses requests and runs your functions, with no framework, and is fast enough for production as it is.

Since Go 1.22 its router, http.ServeMux, understands methods and wildcards in route patterns, so GET /api/bookings/{id} works the way a routes/api.php line does. Today: a server, routes, handlers, path and query values, and JSON responses.

A server

1. One route, one handler

A handler is a function with the signature func(w http.ResponseWriter, r *http.Request): r is the request, and whatever you write to w is the response. mux.HandleFunc(pattern, handler) registers it, and http.ListenAndServe serves the mux on a port.

main.go
package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"os"
)

func health(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "ok")
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /api/health", health)

	slog.Info("listening", "addr", ":8080")
	if err := http.ListenAndServe(":8080", mux); err != nil {
		slog.Error("server stopped", "err", err)
		os.Exit(1)
	}
}
$ curl -s -i http://127.0.0.1:8080/api/health
HTTP/1.1 200 OK
Content-Length: 3
Content-Type: text/plain; charset=utf-8

ok
$ curl -s -i -X POST http://127.0.0.1:8080/api/health
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Content-Length: 19

Method Not Allowed
$ curl -s -i http://127.0.0.1:8080/api/nothing
HTTP/1.1 404 Not Found
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Content-Length: 19

404 page not found
the server’s log (stderr), after Ctrl-C
2026/12/03 19:02:06 INFO listening addr=:8080

curl -i shows the status line and the headers. Three requests, three answers, and you wrote only the first: a POST to a GET route gets 405 Method Not Allowed with an Allow header, and a path no route matches gets 404. Go sets Content-Type from the first bytes when you do not.

ListenAndServe runs until the program stops, handling each request in its own goroutine (the goroutines lesson). It returns only on an error, such as the port being taken, which is why its error is logged and fatal. The shutdown lesson stops it cleanly instead of with Ctrl-C.

Routes

2. A wildcard: {id} and PathValue

{id} in a pattern matches one segment of the path; r.PathValue("id") returns it as a string. Converting it to a number, and saying what happens when it is not one, is your job.

main.go
package main

import (
	"encoding/json/v2"
	"log/slog"
	"net/http"
	"os"
	"strconv"
)

type Booking struct {
	ID     int64  `json:"id"`
	Guest  string `json:"guest"`
	Nights int    `json:"nights"`
	Status string `json:"status"`
}

var bookings = []Booking{
	{ID: 5521, Guest: "Lina", Nights: 3, Status: "confirmed"},
	{ID: 5522, Guest: "Omar", Nights: 7, Status: "pending"},
	{ID: 5523, Guest: "Sara", Nights: 2, Status: "pending"},
}

// writeJSON sends v as a JSON response with the given status.
func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.MarshalWrite(w, v); err != nil {
		slog.Error("writing the response", "err", err)
	}
}

func showBooking(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"message": "Not Found"})
		return
	}
	for _, b := range bookings {
		if b.ID == id {
			writeJSON(w, http.StatusOK, map[string]Booking{"data": b})
			return
		}
	}
	writeJSON(w, http.StatusNotFound, map[string]string{"message": "No booking " + strconv.FormatInt(id, 10)})
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /api/bookings/{id}", showBooking)

	slog.Info("listening", "addr", ":8080")
	if err := http.ListenAndServe(":8080", mux); err != nil {
		slog.Error("server stopped", "err", err)
		os.Exit(1)
	}
}
$ curl -s -i http://127.0.0.1:8080/api/bookings/5522
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 65

{"data":{"id":5522,"guest":"Omar","nights":7,"status":"pending"}}
$ curl -s -i http://127.0.0.1:8080/api/bookings/9999
HTTP/1.1 404 Not Found
Content-Type: application/json
Content-Length: 29

{"message":"No booking 9999"}
$ curl -s -i http://127.0.0.1:8080/api/bookings/abc
HTTP/1.1 404 Not Found
Content-Type: application/json
Content-Length: 23

{"message":"Not Found"}
the server’s log (stderr), after Ctrl-C
2026/12/03 19:02:07 INFO listening addr=:8080

strconv.ParseInt(text, 10, 64) parses a base-10 number into an int64, the type of a Laravel id(). A non-number is answered like a route that does not exist, the same as Laravel’s ->whereNumber('id').

writeJSON sets the header before WriteHeader: once the status line is sent, headers can no longer change. Its error is only logged, because by then the status has gone out and there is no way to tell the client anything else. The response is {"data": …}, the shape of a Laravel API resource.

3. The query string

r.URL.Query() parses ?status=pending&per_page=2 into a map of values; .Get(name) returns the first value, or "" when it is missing.

main.go
package main

import (
	"encoding/json/v2"
	"log/slog"
	"net/http"
	"os"
)

type Booking struct {
	ID     int64  `json:"id"`
	Guest  string `json:"guest"`
	Nights int    `json:"nights"`
	Status string `json:"status"`
}

var bookings = []Booking{
	{ID: 5521, Guest: "Lina", Nights: 3, Status: "confirmed"},
	{ID: 5522, Guest: "Omar", Nights: 7, Status: "pending"},
	{ID: 5523, Guest: "Sara", Nights: 2, Status: "pending"},
}

// writeJSON sends v as a JSON response with the given status.
func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.MarshalWrite(w, v); err != nil {
		slog.Error("writing the response", "err", err)
	}
}

func listBookings(w http.ResponseWriter, r *http.Request) {
	status := r.URL.Query().Get("status")

	matching := []Booking{}
	for _, b := range bookings {
		if status == "" || b.Status == status {
			matching = append(matching, b)
		}
	}
	writeJSON(w, http.StatusOK, map[string][]Booking{"data": matching})
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /api/bookings", listBookings)

	slog.Info("listening", "addr", ":8080")
	if err := http.ListenAndServe(":8080", mux); err != nil {
		slog.Error("server stopped", "err", err)
		os.Exit(1)
	}
}
$ curl -s -i 'http://127.0.0.1:8080/api/bookings?status=pending'
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 124

{"data":[{"id":5522,"guest":"Omar","nights":7,"status":"pending"},{"id":5523,"guest":"Sara","nights":2,"status":"pending"}]}
$ curl -s -i 'http://127.0.0.1:8080/api/bookings?status=cancelled'
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 11

{"data":[]}
the server’s log (stderr), after Ctrl-C
2026/12/03 19:02:08 INFO listening addr=:8080

matching := []Booking{} starts as an empty slice. With v2 a nil slice would also be written as [], but saying it in the code makes the intent visible to the next reader.

4. How patterns match

PatternMatchesLaravel
GET /api/bookingsexactly that path, GET and HEADRoute::get('/api/bookings', …)
POST /api/bookingsexactly that path, POST onlyRoute::post(…)
GET /api/bookings/{id}one segment: /api/bookings/5522, not /api/bookings/5522/payments{id}
GET /files/{path...}everything after /files/, slashes included{path} with ->where('path', '.*')
GET /{$}only /Route::get('/', …)
/static/every path that starts with /static/, any methoda prefix group

When two patterns match the same request, the more specific one wins, whatever the order you registered them in: GET /api/bookings/latest beats GET /api/bookings/{id} for that path. Two patterns that are equally specific for some path are a mistake, and HandleFunc panics at startup to tell you, before the server ever runs.

Coming from PHP

routes/api.php
<?php
use App\Http\Controllers\BookingController;
use Illuminate\Support\Facades\Route;

Route::get('/health', fn () => 'ok');
Route::get('/bookings', [BookingController::class, 'index']);
Route::get('/bookings/{id}', [BookingController::class, 'show'])->whereNumber('id');

The routes read almost the same. What Laravel adds around them, Go leaves to you: the response is not built from a return value but written to w, a missing model does not throw ModelNotFoundException, and nothing converts {id} to an int.

The other half is the process. PHP-FPM starts a fresh PHP for each request and forgets everything after it; the Go server is one long-running process, so a package-level variable like bookings lives as long as the server, and every request goroutine sees the same one. That is a feature for caches and connection pools, and a data race waiting to happen for anything a handler changes.

PracticeLearn Go with Tests: HTTP Server; one more route

Do HTTP Server in Learn Go with Tests, the first chapter of its “Build an application” part. It builds a server test-first; the tests lesson of this week does the same with httptest.

Exercise: a booking’s nights

Add GET /api/bookings/{id}/nights, which answers {"data": {"id": 5522, "nights": 7}}. Move the lookup into a function findBooking(id int64) (Booking, bool) used by both handlers. Check that /api/bookings/5522/nights does not reach showBooking, and that POST to it is a 405.

Remember

  • Routes are METHOD /path/{id} patterns on an http.ServeMux; the mux answers 404 and 405 for you.
  • Set headers before WriteHeader, and convert every path value yourself.

Tomorrow: JSON request bodies, validated like a Form Request, with a Laravel-shaped 422.