Files
hspguard/cmd/hspguard/api/api.go
2025-05-18 20:04:36 +02:00

58 lines
1.3 KiB
Go

package api
import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"gitea.local/admin/hspguard/internal/repository"
"gitea.local/admin/hspguard/internal/user"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
type APIServer struct {
addr string
repo *repository.Queries
}
func NewAPIServer(addr string, db *repository.Queries) *APIServer {
return &APIServer{
addr: addr,
repo: db,
}
}
func (s *APIServer) Run() error {
router := chi.NewRouter()
router.Use(middleware.Logger)
workDir, _ := os.Getwd()
staticDir := http.Dir(filepath.Join(workDir, "static"))
FileServer(router, "/static", staticDir)
router.Route("/api/v1", func(r chi.Router) {
userHandler := user.NewUserHandler()
userHandler.RegisterRoutes(router, r)
})
// Handle unknown routes
router.NotFound(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
_, _ = fmt.Fprint(w, `{"error": "404 - route not found"}`)
})
router.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprint(w, `{"error": "405 - method not allowed"}`)
})
log.Println("Listening on", s.addr)
return http.ListenAndServe(s.addr, router)
}