feat: http api server
This commit is contained in:
50
cmd/hspguard/api/api.go
Normal file
50
cmd/hspguard/api/api.go
Normal file
@ -0,0 +1,50 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"gitea.local/admin/hspguard/internal/repository"
|
||||
"gitea.local/admin/hspguard/internal/user"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
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.Route("/api/v1", func(r chi.Router) {
|
||||
userHandler := user.NewUserHandler()
|
||||
userHandler.RegisterRoutes(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)
|
||||
}
|
||||
|
Reference in New Issue
Block a user