HTTP servers
| HandleFunc routes | |
| ListenAndServe | |
| Serve JSON | |
| Graceful shutdown sketch |
HandleFunc routes
The net/http package routes requests with plain functions, no framework needed. HandleFunc binds a path pattern to a handler on the default mux. Each handler receives a writer for the response and a request to read from. Two routes are enough to see the shape of every Go server.
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello, web")
}
func bye(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "bye, web")
}
func main() {
http.HandleFunc("/hello", hello)
http.HandleFunc("/bye", bye)
http.ListenAndServe(":8080", nil)
}
Patterns match path prefixes, so /hello also covers /hello/extra unless a longer pattern wins. Handlers run in their own goroutine per request, so shared state needs locking. The sync lesson later shows Mutex for exactly that case.
ListenAndServe
ListenAndServe opens the port and blocks forever serving requests. It returns only on failure, so wrap it in log.Fatal to surface startup errors. The address has the form host:port, and an empty host means all interfaces. Run the server, then query it from a second terminal.
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello, web")
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
curl localhost:8080/hello
hello, web
Serve JSON
APIs answer with JSON instead of plain text. Set the Content-Type header before writing, then encode the value straight into the response writer. Encoding to the writer avoids building the whole body in memory. The JSON lesson earlier covers tags that shape the output.
package main
import (
"encoding/json"
"net/http"
)
type Status struct {
OK bool `json:"ok"`
Name string `json:"name"`
}
func status(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(Status{OK: true, Name: "api"})
}
func main() {
http.HandleFunc("/status", status)
http.ListenAndServe(":8080", nil)
}
curl localhost:8080/status
{"ok":true,"name":"api"}
Graceful shutdown sketch
Production servers finish in-flight requests before they exit. The sketch below listens for interrupt signals, then gives handlers five seconds to drain. Shutdown with a timeout context is the standard recipe. Copy this shape into every long-lived service you write.
package main
import (
"context"
"fmt"
"net/http"
"os/signal"
"syscall"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello, web")
})
srv := &http.Server{Addr: ":8080", Handler: mux}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
go func() {
<-ctx.Done()
shut, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(shut)
}()
srv.ListenAndServe()
}
NotifyContext turns OS signals into a context that closes itself on Ctrl+C. The goroutine waits for that moment and then drains the server. Contexts get a full lesson of their own two chapters ahead.
Next: HTTP clients
Article author: Arthur Isaev