← Retour au cours: Go from scratch

JSON and a REST tasks API

Vidéo bientôt disponible

A REST API is a server that exposes resources (tasks, users, products) through routes and HTTP methods, and that almost always speaks JSON. GET reads, POST creates, PUT or PATCH modify and DELETE removes. In this lesson you learn to convert Go structs to JSON and back with the encoding/json package, and you set up the first operations of the tasks API that you will finish in the final project: list and create. The data will live in memory, protected with a Mutex, because you know from week 7 that several requests are served at the same time, each one in its own goroutine.

From struct to JSON and from JSON to struct

json.Marshal converts a Go value into JSON bytes, and json.Unmarshal does the opposite, receiving a pointer to the destination. Only fields starting with an uppercase letter are exported, because the package reads them by reflection. Struct tags between backticks control the name in JSON: json:"title" writes it in lowercase, json:"-" hides it and json:"note,omitempty" omits it when empty. If you forget the tags, the JSON will come out with Go names (Title, Done), which is not usual in an API. Always check the error returned by Marshal and Unmarshal: malformed JSON is normal input, not an exception.

go
package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Task struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

func main() {
	t := Task{ID: 1, Title: "Learn Go"}
	data, err := json.Marshal(t)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(data)) // {"id":1,"title":"Learn Go","done":false}

	var back Task
	input := []byte(`{"id":2,"title":"Write tests","done":true}`)
	if err := json.Unmarshal(input, &back); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", back) // {ID:2 Title:Write tests Done:true}
}

The store and the handlers

First an in-memory store: a map of tasks, a counter for the identifiers and a Mutex, because each request runs in its own goroutine. The store methods take the lock, and the handlers live in an API struct that holds it. To answer JSON we use a writeJSON helper that sets the Content-Type header, writes the status code and encodes the value. To read a request body you use json.NewDecoder(r.Body).Decode(&destination); if it fails or the title is empty, the right answer is 400, because the fault is the client's, not yours.

go
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"strconv"
	"sync"
)

type Task struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

type Store struct {
	mu     sync.Mutex
	nextID int
	tasks  map[int]Task
}

func NewStore() *Store {
	return &Store{nextID: 1, tasks: make(map[int]Task)}
}

func (s *Store) Add(title string) Task {
	s.mu.Lock()
	defer s.mu.Unlock()
	t := Task{ID: s.nextID, Title: title}
	s.tasks[t.ID] = t
	s.nextID++
	return t
}

func (s *Store) List() []Task {
	s.mu.Lock()
	defer s.mu.Unlock()
	list := make([]Task, 0, len(s.tasks)) // never nil: JSON gives [] not null
	for id := 1; id < s.nextID; id++ {
		if t, ok := s.tasks[id]; ok {
			list = append(list, t)
		}
	}
	return list
}

func (s *Store) Get(id int) (Task, bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	t, ok := s.tasks[id]
	return t, ok
}

type API struct{ store *Store }

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(v); err != nil {
		log.Println("encode error:", err)
	}
}

func (a *API) list(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, http.StatusOK, a.store.List())
}

func (a *API) create(w http.ResponseWriter, r *http.Request) {
	var in struct {
		Title string `json:"title"`
	}
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Title == "" {
		http.Error(w, "invalid JSON or empty title", http.StatusBadRequest)
		return
	}
	writeJSON(w, http.StatusCreated, a.store.Add(in.Title))
}

func (a *API) get(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		http.Error(w, "invalid id", http.StatusBadRequest)
		return
	}
	t, ok := a.store.Get(id)
	if !ok {
		http.Error(w, "task not found", http.StatusNotFound)
		return
	}
	writeJSON(w, http.StatusOK, t)
}

func newMux(a *API) *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /tasks", a.list)
	mux.HandleFunc("POST /tasks", a.create)
	mux.HandleFunc("GET /tasks/{id}", a.get)
	return mux
}

func main() {
	api := &API{store: NewStore()}
	log.Println("listening on :8080")
	log.Fatal(http.ListenAndServe(":8080", newMux(api)))
}

Try it with curl: curl -X POST -d '{"title":"Buy milk"}' http://localhost:8080/tasks returns 201 with the created task, and curl http://localhost:8080/tasks returns the list. Notice three design details. One: List creates the slice with make so an empty list is serialised as [] and not null, which breaks many clients. Two: the store knows nothing about HTTP, only about tasks, so you can test it separately. Three: each handler chooses the right code: 201 when creating, 404 if it does not exist, 400 if the body is invalid.

  • json.Marshal / json.Unmarshal convert between structs and JSON.
  • Only uppercase fields are exported; tags set the name.
  • Decode the body with json.NewDecoder(r.Body); client error = 400.
  • Data shared between requests: protect it with a Mutex.
  • 201 when creating, 404 if missing, 200 when reading.

Testez vos acquis

Question 1 sur 5

What does the tag json:"title" do on a field?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →