Go
HTTP API
Write REST endpoints with net/http.
HTTP API
Since Go 1.22, http.ServeMux supports methods and path variables; most services need no extra router:
mux := http.NewServeMux()
mux.HandleFunc("GET /urunler", h.liste)
mux.HandleFunc("POST /urunler", h.ekle)
mux.HandleFunc("GET /urunler/{id}", h.getir) // r.PathValue("id")
The handler reads JSON with json.NewDecoder(r.Body), writes it with json.NewEncoder(w) and sets the Content-Type: application/json header.
Correct status codes
An API's quality shows in its status codes: a successful list 200, a new record 201 Created, broken JSON 400, a missing record 404, an unexpected error 500.
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
http.Error(w, "geçersiz JSON", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
Exercise List endpoint
Write a handler for GET /urunler that returns [{"ad":"Kalem"}] (use json.NewEncoder(w).Encode). Send a request with httptest and print the response body.
Show example solution
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
)
type Urun struct {
Ad string `json:"ad"`
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /urunler", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode([]Urun{{Ad: "Kalem"}})
})
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/urunler", nil))
fmt.Print(rec.Body.String())
}
Test yourself
-
How is the id value read with the pattern <code>"GET /urunler/{id}"</code>?
- r.PathValue("id")
- r.URL.Query().Get("id")
- r.Header.Get("id")
- mux.Var("id")
Show answer
r.PathValue("id") — The Go 1.22 ServeMux stores path variables in the request; PathValue reads them. Query() reads query parameters like ?id=....
-
New record code
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.____)
json.NewEncoder(w).Encode(u)
Show answer
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(u)
-
Situation and code
- List returned
- 200
- Product added
- 201
- Bozuk JSON
- 400
- No such product
- 404
Next lesson: Docker and deployment