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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?