Creating an HTTP Server
ListenAndServe, HandlerFunc, and ServeMux
Creating an HTTP Server is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
net/http package
Go's standard library net/http provides a production-capable HTTP/1.1 and HTTP/2 server without external dependencies.
Basic server
Register a handler with http.HandleFunc and start listening with http.ListenAndServe:
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
})
log.Fatal(http.ListenAndServe(":8080", nil))http.Handler interface
Any type implementing ServeHTTP(ResponseWriter, *Request) is an http.Handler. Use it for stateful handlers that embed a database or config.
type App struct{ db *sql.DB }
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// use a.db
}ServeMux
http.NewServeMux() creates an isolated router. Pass it to http.ListenAndServe to avoid the global default mux (safer in libraries).
mux := http.NewServeMux()
mux.HandleFunc("/api/users", usersHandler)
http.ListenAndServe(":8080", mux)Responding with status codes
Write the status code with w.WriteHeader(code) before writing the body. If you only call w.Write, the status defaults to 200.
w.WriteHeader(http.StatusCreated)
w.Write([]byte("created"))Writing JSON responses
Set Content-Type before writing the body, then encode with json.Encoder:
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)Reading the request
Access method, URL, headers, query params, and body via the *Request struct.
r.Method // "GET", "POST", ...
r.URL.Path // "/api/users"
r.URL.Query().Get("id") // query param
r.Header.Get("Authorization")Parsing JSON request body
Decode the request body with json.Decoder. Limit body size with http.MaxBytesReader to prevent memory exhaustion.
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
var req CreateUserRequest
json.NewDecoder(r.Body).Decode(&req)Server configuration
Configure timeouts with a custom http.Server to prevent slow-client attacks:
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
srv.ListenAndServe()HTTPS
Use srv.ListenAndServeTLS(certFile, keyFile) to serve HTTPS. Certificates can be self-signed (dev) or from Let's Encrypt (prod via golang.org/x/crypto/acme/autocert).
Handler composition
Wrap handlers to add cross-cutting concerns (logging, auth, recovery) without modifying business logic. Return the next handler after modification.
Quick Check
Why should you set ReadTimeout and WriteTimeout on an http.Server?
Recap: Creating an HTTP Server
Key points:
- HandleFunc + ListenAndServe for simple servers
- Custom http.Server with timeouts for production
- ServeMux for isolated routing
- json.NewEncoder(w) for JSON responses
Frequently asked questions
Is the “Creating an HTTP Server” lesson free?
Yes — the full text of “Creating an HTTP Server” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Creating an HTTP Server”?
ListenAndServe, HandlerFunc, and ServeMux You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Creating an HTTP Server” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating an HTTP Server
- Routing and Path Parameters
- Middleware Pattern
- Graceful Shutdown