Refactor to JSON API with Chi router and interface-based design

- Add pkg/greet/api_v1.go with ApiV1Greet interface and handler
- Implement Greeter interface for dependency injection
- Return JSON responses with proper Content-Type headers
- Move greet service instantiation to server package
- Separate v1 route registration into registerApiV1Routes function
- Health endpoint at /api level, greet endpoints at /api/v1/greet
- Simplify server entrypoint by removing external dependencies
This commit is contained in:
Gabriel Radureau
2026-04-03 13:04:33 +02:00
parent 04d34bead1
commit 6365f92359
8 changed files with 134 additions and 4 deletions

58
pkg/server/server.go Normal file
View File

@@ -0,0 +1,58 @@
package server
import (
"net/http"
"DanceLessonsCoach/pkg/greet"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
type Server struct {
router *chi.Mux
}
func NewServer() *Server {
s := &Server{
router: chi.NewRouter(),
}
s.setupRoutes()
return s
}
func (s *Server) setupRoutes() {
s.router.Use(middleware.Logger)
s.router.Route("/api", func(r chi.Router) {
r.Use(s.apiMiddlewares()...)
r.Get("/health", s.handleHealth)
s.registerApiV1Routes(r)
})
}
func (s *Server) registerApiV1Routes(r chi.Router) {
r.Route("/v1", func(r chi.Router) {
greetService := greet.NewService()
greetHandler := greet.NewApiV1GreetHandler(greetService)
r.Route("/greet", func(r chi.Router) {
greetHandler.RegisterRoutes(r)
})
})
}
func (s *Server) apiMiddlewares() []func(http.Handler) http.Handler {
return []func(http.Handler) http.Handler{
middleware.StripSlashes,
middleware.Recoverer,
}
}
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"status":"healthy"}`))
}
func (s *Server) Router() http.Handler {
return s.router
}