Lesson 21 of 60 · Go
Building a RESTful API – CRUD Operations
Duration: 30 minutes
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 bool `json:"done"`
}
var (
store = map[int]Todo{}
nextID = 1
storeMu sync.RWMutex
)
// Create
func createTodo(w http.ResponseWriter, r *http.Request) {
var 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)
}
// Read (list)
func listTodos(w http.ResponseWriter, r *http.Request) {
storeMu.RLock()
defer storeMu.RUnlock()
var list []Todo
for _, v := range store { list = append(list, v) }
json.NewEncoder(w).Encode(list)
}
Register handlers with a router (http.ServeMux or chi).