CodeBlanks Logo Icon CodeBlanks

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)

Practice 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.

Starter code

main.go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
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())
}

Expected output

[{"ad":"Kalem"}]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is the id value read with the pattern <code>"GET /urunler/{id}"</code>?

  • r.PathValue("id") Correct answer
  • r.URL.Query().Get("id")
  • r.Header.Get("id")
  • mux.Var("id")

Explanation: The Go 1.22 ServeMux stores path variables in the request; PathValue reads them. Query() reads query parameters like ?id=....

2 New record code

Question
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.____)
json.NewEncoder(w).Encode(u)
Answer
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(u)

Explanation: 201 Created reports that a new resource was created.

3 Situation and code

Term Meaning
List returned 200
Product added 201
Bozuk JSON 400
No such product 404

All lessons in Advanced