Your first HTTP server with net/http
Go shines in servers, and the proof is that you can write a complete one with only the standard library, installing nothing. The net/http package has everything: it listens on a port, parses requests, routes them to your functions and sends the responses. In this lesson you build a small server and test it without opening the browser. It is the base of the REST API in the next two lessons, so it is worth understanding each piece well: the handler, the route multiplexer and the status code.
Handlers and routes
A handler is a function with two parameters: http.ResponseWriter, where you write the response, and *http.Request, which describes the request (method, path, headers, body). The http.ServeMux decides which handler serves each route. Since Go 1.22 the pattern can include the method and variable parts: "GET /hello/{name}" accepts only GET, and r.PathValue("name") returns the variable piece. If the route exists but the method does not, the server answers 405 automatically; if the route does not exist, 404. Create your own mux with http.NewServeMux() instead of using the global one: it is easier to test.
package main
import (
"fmt"
"log"
"net/http"
)
func health(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "ok")
}
func hello(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
fmt.Fprintf(w, "Hello, %s!\n", name)
}
// newMux builds the router; keeping it in a function makes it testable.
func newMux() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /health", health)
mux.HandleFunc("GET /hello/{name}", hello)
return mux
}
func main() {
addr := ":8080"
log.Println("listening on", addr)
if err := http.ListenAndServe(addr, newMux()); err != nil {
log.Fatal(err)
}
}Run go run . and, in another terminal, try curl http://localhost:8080/hello/Ana: you will see "Hello, Ana!". ListenAndServe blocks until an error happens, which is why its result is checked and log.Fatal is used. A frequent mistake at the start is that the port is already in use ("address already in use"): close the other program or change the port.
Parameters, status codes and errors
The query part (?a=1&b=2) is read with r.URL.Query().Get("a"), which always returns a string: you convert and validate it. If something is wrong, answer with http.Error(w, message, code). The status code tells what happened: 200 correct, 201 created, 400 bad request from the client, 404 not found, 500 internal failure. Important: you must set the header and the code before writing the body. The first write sends 200 by default, and afterwards you can no longer change it; and after http.Error do a return, or your handler will keep running and write a second response.
// add handles GET /add?a=1&b=2 and answers with the sum.
func add(w http.ResponseWriter, r *http.Request) {
a, errA := strconv.Atoi(r.URL.Query().Get("a"))
b, errB := strconv.Atoi(r.URL.Query().Get("b"))
if errA != nil || errB != nil {
http.Error(w, "a and b must be integers", http.StatusBadRequest)
return // do not keep writing after an error
}
fmt.Fprintln(w, a+b)
}Testing without starting the server
The net/http/httptest package lets you test handlers without a network: httptest.NewRequest creates a fake request and httptest.NewRecorder captures the response (code, headers and body). You call mux.ServeHTTP(rec, req) and check the result as in any test. These tests are fast, use no ports and depend on nothing external, so you can run them thousands of times. That is why we separated newMux from main.
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHello(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/hello/Ana", nil)
rec := httptest.NewRecorder()
newMux().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d; want %d", rec.Code, http.StatusOK)
}
if got, want := rec.Body.String(), "Hello, Ana!\n"; got != want {
t.Errorf("body = %q; want %q", got, want)
}
}
func TestWrongMethod(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/health", nil)
rec := httptest.NewRecorder()
newMux().ServeHTTP(rec, req)
if rec.Code != http.StatusMethodNotAllowed {
t.Errorf("status = %d; want 405", rec.Code)
}
}- A handler is func(w http.ResponseWriter, r *http.Request).
- "GET /path/{id}" and r.PathValue("id") (Go 1.22+).
- Set headers and code before the body; return after http.Error.
- Test with httptest.NewRequest and NewRecorder, with no network.
Testez vos acquis
Question 1 sur 5What signature does a net/http handler have?
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères