- Added /api/v2/greet POST endpoint with JSON request/response - Implemented ServiceV2 with Hello my friend <name>! greeting format - Added api.v2_enabled feature flag (default: false) - Extended BDD tests to cover v2 scenarios - Maintained full backward compatibility with v1 API - Added DLC_API_V2_ENABLED environment variable support - Created ADR 0010-api-v2-feature-flag.md - Updated configuration system to support API versioning
68 lines
1.5 KiB
Go
68 lines
1.5 KiB
Go
package greet
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
type GreeterV2 interface {
|
|
GreetV2(ctx context.Context, name string) string
|
|
}
|
|
|
|
type ApiV2Greet interface {
|
|
RegisterRoutes(router chi.Router)
|
|
}
|
|
|
|
type apiV2GreetHandler struct {
|
|
greeter GreeterV2
|
|
}
|
|
|
|
func NewApiV2GreetHandler(greeter GreeterV2) ApiV2Greet {
|
|
return &apiV2GreetHandler{greeter: greeter}
|
|
}
|
|
|
|
func (h *apiV2GreetHandler) RegisterRoutes(router chi.Router) {
|
|
log.Trace().Msg("Registering v2 greet routes")
|
|
router.Post("/", h.handleGreetPost)
|
|
log.Trace().Msg("v2 Greet routes registered")
|
|
}
|
|
|
|
type greetRequest struct {
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
type greetResponse struct {
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
func (h *apiV2GreetHandler) handleGreetPost(w http.ResponseWriter, r *http.Request) {
|
|
// Read request body
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, `{"error":"failed to read request body"}`, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Parse JSON
|
|
var req greetRequest
|
|
if err := json.Unmarshal(body, &req); err != nil {
|
|
http.Error(w, `{"error":"invalid JSON format"}`, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Call service
|
|
message := h.greeter.GreetV2(r.Context(), req.Name)
|
|
|
|
// Write response
|
|
h.writeJSONResponse(w, message)
|
|
}
|
|
|
|
func (h *apiV2GreetHandler) writeJSONResponse(w http.ResponseWriter, message string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(greetResponse{Message: message})
|
|
} |