You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

77 lines
1.7 KiB

package api
import (
"encoding/json"
"log"
"net/http"
"git.brettb.xyz/goinv/server/internal/storage"
"git.brettb.xyz/goinv/server/internal/types"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
)
const API_VERSION_MAJOR = 0
const API_VERSION_MINOR = 0
const API_VERSION_PATCH = 1
var API_VERSION = types.APIVersion{
Major: API_VERSION_MAJOR,
Minor: API_VERSION_MINOR,
Patch: API_VERSION_PATCH,
}
type APIFunc func(w http.ResponseWriter, r *http.Request) error
type APIServer struct {
listenAddr string
db *storage.DataStore
}
func NewAPIServer(database *storage.DataStore, listenAddr string) *APIServer {
return &APIServer{
listenAddr: listenAddr,
db: database,
}
}
func (s *APIServer) Run() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(render.SetContentType(render.ContentTypeJSON))
s.registerRoutes(r)
log.Printf("API Server listening on %s", s.listenAddr)
err := http.ListenAndServe(s.listenAddr, r)
if err != nil {
panic(err)
}
}
func (s *APIServer) registerRoutes(r *chi.Mux) {
r.Get("/", makeHandler(s.handleIndex))
r.Route("/assets", s.setupAssetRoutes())
r.Route("/shelves", s.setupShelfRoutes())
}
func (s *APIServer) handleIndex(w http.ResponseWriter, r *http.Request) error {
return writeJSON(w, http.StatusOK, types.IndexResponse{Version: API_VERSION})
}
func makeHandler(f APIFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
render.Render(w, r, errBadRequest(err))
}
}
}
func writeJSON(w http.ResponseWriter, s int, v any) error {
w.WriteHeader(s)
return json.NewEncoder(w).Encode(v)
}