feat(api): add HTTP server with full REST API

Chi router with all entity CRUD endpoints, promote/demote/use
actions, tag listing. CORS middleware for --dev mode. Graceful
shutdown on SIGINT/SIGTERM. 22 API integration tests via httptest.
This commit is contained in:
2026-05-14 11:30:47 -04:00
parent c3cc9464b9
commit 6de174e474
6 changed files with 987 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
package api
import (
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/lerko/nib/internal/db"
)
func NewRouter(store *db.Store, devMode bool) chi.Router {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
if devMode {
r.Use(corsMiddleware)
}
r.Route("/api", func(r chi.Router) {
r.Use(jsonContentType)
r.Get("/entities", listEntities(store))
r.Post("/entities", createEntity(store))
r.Get("/entities/{id}", getEntity(store))
r.Put("/entities/{id}", updateEntity(store))
r.Delete("/entities/{id}", deleteEntity(store))
r.Post("/entities/{id}/promote", promoteEntity(store))
r.Post("/entities/{id}/demote", demoteEntity(store))
r.Post("/entities/{id}/use", useEntity(store))
r.Get("/tags", listTags(store))
})
return r
}
func jsonContentType(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
next.ServeHTTP(w, r)
})
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}