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:
44
pkg/greet/api_v1.go
Normal file
44
pkg/greet/api_v1.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package greet
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type Greeter interface {
|
||||
Greet(name string) string
|
||||
}
|
||||
|
||||
type ApiV1Greet interface {
|
||||
RegisterRoutes(router chi.Router)
|
||||
}
|
||||
|
||||
type apiV1GreetHandler struct {
|
||||
greeter Greeter
|
||||
}
|
||||
|
||||
func NewApiV1GreetHandler(greeter Greeter) ApiV1Greet {
|
||||
return &apiV1GreetHandler{greeter: greeter}
|
||||
}
|
||||
|
||||
func (h *apiV1GreetHandler) RegisterRoutes(router chi.Router) {
|
||||
router.Get("/", h.handleGreetQuery)
|
||||
router.Get("/{name}", h.handleGreetPath)
|
||||
}
|
||||
|
||||
func (h *apiV1GreetHandler) handleGreetQuery(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.URL.Query().Get("name")
|
||||
h.writeJSONResponse(w, h.greeter.Greet(name))
|
||||
}
|
||||
|
||||
func (h *apiV1GreetHandler) handleGreetPath(w http.ResponseWriter, r *http.Request) {
|
||||
name := chi.URLParam(r, "name")
|
||||
h.writeJSONResponse(w, h.greeter.Greet(name))
|
||||
}
|
||||
|
||||
func (h *apiV1GreetHandler) writeJSONResponse(w http.ResponseWriter, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"message": message})
|
||||
}
|
||||
Reference in New Issue
Block a user