How do I build a REST API with Chi in Go?

Building a REST API in Go using the Chi router is a straightforward and efficient process. Chi is a lightweight and fast HTTP router for building Go HTTP services, making it an excellent choice for creating RESTful APIs. In this example, we'll walk through creating a simple CRUD API.

Go, Chi, REST API, HTTP Router, CRUD, Go web development

This guide provides an overview of how to build a REST API in Go using the Chi framework, focusing on creating, reading, updating, and deleting resources in an efficient manner.

package main import ( "net/http" "github.com/go-chi/chi/v5" "encoding/json" ) type Item struct { ID string `json:"id"` Name string `json:"name"` } var items = []Item{ {ID: "1", Name: "Item One"}, {ID: "2", Name: "Item Two"}, } func main() { r := chi.NewRouter() r.Get("/items", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(items) }) r.Get("/items/{id}", func(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") for _, item := range items { if item.ID == id { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(item) return } } http.NotFound(w, r) }) r.Post("/items", func(w http.ResponseWriter, r *http.Request) { var newItem Item json.NewDecoder(r.Body).Decode(&newItem) items = append(items, newItem) w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(newItem) }) r.Put("/items/{id}", func(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") var updatedItem Item json.NewDecoder(r.Body).Decode(&updatedItem) for i, item := range items { if item.ID == id { items[i] = updatedItem updatedItem.ID = id w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(updatedItem) return } } http.NotFound(w, r) }) r.Delete("/items/{id}", func(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") for i, item := range items { if item.ID == id { items = append(items[:i], items[i+1:]...) w.WriteHeader(http.StatusNoContent) return } } http.NotFound(w, r) }) http.ListenAndServe(":8080", r) }

Go Chi REST API HTTP Router CRUD Go web development