Lesson 21 of 60
GoBuilding a RESTful API – CRUD Operations
30 minutes
Course progress35%
A Minimal CRUD API
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
We will build a tiny in‑memory Todo API.
type Todo struct {
ID int `json:"id"`
Task string `json:"task"`
Done
}
(
store = []Todo{}
nextID =
storeMu sync.RWMutex
)
{
t Todo
json.NewDecoder(r.Body).Decode(&t)
storeMu.Lock()
t.ID = nextID
nextID++
store[t.ID] = t
storeMu.Unlock()
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(t)
}
{
storeMu.RLock()
storeMu.RUnlock()
list []Todo
_, v := store { list = (list, v) }
json.NewEncoder(w).Encode(list)
}