Understand the contract
net/http connects requests to handlers. A handler receives a ResponseWriter and a Request, inspects the request and writes a response. Start with a local endpoint whose method, path and body are explicit. Keep business logic separate so it can be tested without starting a network listener.
The example uses a dedicated ServeMux and a GET /hello pattern, supported by the modern standard-library router. A Server struct exposes timeouts that are easy to miss with a convenience call. Binding to 127.0.0.1 keeps the exercise on the local machine.
Work through the example
Run the program and visit http://127.0.0.1:8080/hello with a browser or curl. Set Content-Type before writing the body; the first write can commit response headers. A GET pattern also accepts HEAD under ServeMux rules. Stop this introductory process with the terminal’s interrupt command.
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "Hello, Go!")
})
server := &http.Server{
Addr: "127.0.0.1:8080", Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
log.Fatal(server.ListenAndServe())
}Watch this boundary
A local server example is not a complete deployment configuration. Timeout values here are illustrative and need workload-specific decisions. Handlers can run concurrently, so a shared map or counter added later requires synchronization. The final project shows handler testing, and the concurrency block explains shared-state protection.
Practice with a changed input
Add a second read-only route with its own content type. Send a POST to /hello and inspect the method rejection, then test an unknown path.
Lesson 39 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services