feat: scaffold go backend foundation
This commit is contained in:
47
internal/httpapi/handler.go
Normal file
47
internal/httpapi/handler.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"tutor/internal/config"
|
||||
"tutor/internal/workflows"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
cfg config.Config
|
||||
runner workflows.Runner
|
||||
}
|
||||
|
||||
func NewHandler(cfg config.Config, runner workflows.Runner) Handler {
|
||||
return Handler{
|
||||
cfg: cfg,
|
||||
runner: runner,
|
||||
}
|
||||
}
|
||||
|
||||
func (h Handler) Routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", h.health)
|
||||
return mux
|
||||
}
|
||||
|
||||
func (h Handler) health(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, healthResponse{
|
||||
Status: "ok",
|
||||
Environment: h.cfg.Environment,
|
||||
ModelKey: h.cfg.ModelKey,
|
||||
})
|
||||
}
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
Environment string `json:"environment"`
|
||||
ModelKey string `json:"model_key"`
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
42
internal/httpapi/handler_test.go
Normal file
42
internal/httpapi/handler_test.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"tutor/internal/config"
|
||||
"tutor/internal/workflows"
|
||||
)
|
||||
|
||||
func TestHealth(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
Environment: "test",
|
||||
ModelKey: "deepseek-v4-flash",
|
||||
}
|
||||
handler := NewHandler(cfg, workflows.NewStubRunner())
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
handler.Routes().ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
var body healthResponse
|
||||
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("decode health response: %v", err)
|
||||
}
|
||||
if body.Status != "ok" {
|
||||
t.Fatalf("body.Status = %q", body.Status)
|
||||
}
|
||||
if body.Environment != "test" {
|
||||
t.Fatalf("body.Environment = %q", body.Environment)
|
||||
}
|
||||
if body.ModelKey != "deepseek-v4-flash" {
|
||||
t.Fatalf("body.ModelKey = %q", body.ModelKey)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user