How to Handle 404 and Error Pages in Go

Web
Go requires manual registration of handlers to serve 404 and custom error pages since it does not provide automatic fallback behavior.

Go does not automatically serve 404 or error pages; you must explicitly register a handler for the 404 Not Found status code in your http.ServeMux.

package main

import (
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/not-found", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte("404: Page Not Found"))
	})

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

For global error handling, wrap your ServeMux with a custom http.Handler that checks w.WriteHeader status codes or use http.NotFound as a fallback handler.