Feat: Backend scaffolding and local dev stack
This commit is contained in:
69
Backend/internal/httpx/shared_routes.go
Normal file
69
Backend/internal/httpx/shared_routes.go
Normal file
@@ -0,0 +1,69 @@
|
||||
// Path: Backend/internal/httpx/shared_routes.go
|
||||
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type sharedRoutes struct {
|
||||
cfg RouterConfig
|
||||
}
|
||||
|
||||
func newSharedRoutes(cfg RouterConfig) routeRegistrar {
|
||||
return sharedRoutes{cfg: cfg}
|
||||
}
|
||||
|
||||
func (routes sharedRoutes) Register(router chi.Router) {
|
||||
router.Get("/", routes.handleIndex)
|
||||
router.Get("/health", routes.handleHealth)
|
||||
router.Get("/version", routes.handleVersion)
|
||||
}
|
||||
|
||||
func (routes sharedRoutes) handleIndex(w http.ResponseWriter, _ *http.Request) {
|
||||
WriteJSON(w, http.StatusOK, map[string]string{
|
||||
"service": routes.cfg.ServiceName,
|
||||
"status": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
func (routes sharedRoutes) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
databaseStatus := "ok"
|
||||
if err := routes.cfg.Database.Health(ctx); err != nil {
|
||||
databaseStatus = err.Error()
|
||||
}
|
||||
|
||||
cacheStatus := "ok"
|
||||
if err := routes.cfg.Cache.Health(ctx); err != nil {
|
||||
cacheStatus = err.Error()
|
||||
}
|
||||
|
||||
statusCode := http.StatusOK
|
||||
if databaseStatus != "ok" || cacheStatus != "ok" {
|
||||
statusCode = http.StatusServiceUnavailable
|
||||
}
|
||||
|
||||
WriteJSON(w, statusCode, map[string]any{
|
||||
"service": routes.cfg.ServiceName,
|
||||
"status": map[string]string{
|
||||
"database": databaseStatus,
|
||||
"cache": cacheStatus,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes sharedRoutes) handleVersion(w http.ResponseWriter, _ *http.Request) {
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"service": routes.cfg.ServiceName,
|
||||
"app": routes.cfg.Config.AppName,
|
||||
"environment": routes.cfg.Config.Environment,
|
||||
"build": routes.cfg.BuildInfo,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user