×

go · level 2 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An speaks JSON in both directions.

An API is a server that other programs talk to, usually in JSON. A shop app might send POST /basket with a JSON basket in the , and get a JSON reply back. Your handler reads one and writes the other.

Set a first, so the caller knows what is coming: w.Header().Set("Content-Type", "application/json"). Then w.WriteHeader(http.StatusCreated) can choose the status, 201 here, and json.NewEncoder(w).Encode(reply) writes JSON straight into w.

To read the request body, json.NewDecoder(r.Body).Decode(&basket) fills your value, much like Unmarshal. If it fails, or the data makes no sense, answer 400 for bad request and say why.

package main
import "encoding/json"
import "fmt"
import "net/http"
import "net/http/httptest"
import "strings"
func basket(w http.ResponseWriter, r *http.Request) {
	var items map[string]int
	if err := json.NewDecoder(r.Body).Decode(&items); err != nil {
		http.Error(w, "bad basket", http.StatusBadRequest)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]int{"kinds": len(items)})
}
func main() {
	rec := httptest.NewRecorder()
	basket(rec, httptest.NewRequest("POST", "/basket", strings.NewReader(`{"tea": 2, "cake": 1}`)))
	fmt.Print(rec.Code, " ", rec.Header().Get("Content-Type"), " ", rec.Body.String())
}

strings.NewReader(text) turns a string into something a request body can be read from.