60 lines
1.9 KiB
Go
60 lines
1.9 KiB
Go
package app
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// ---------------------------------------------------------------------
|
|
// HTTP helpers
|
|
// ---------------------------------------------------------------------
|
|
|
|
// EN: Common HTTP helpers used by all endpoint groups for consistent JSON output,
|
|
// EN: lightweight request timing logs, and health probing.
|
|
// RU: Общие HTTP-хелперы для всех групп эндпоинтов: единый JSON-ответ,
|
|
// RU: лёгкое логирование длительности запросов и health-check.
|
|
|
|
// ---------------------------------------------------------------------
|
|
// request logging
|
|
// ---------------------------------------------------------------------
|
|
|
|
func logRequests(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
next.ServeHTTP(w, r)
|
|
log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
|
|
})
|
|
}
|
|
|
|
// ---------------------------------------------------------------------
|
|
// JSON response helper
|
|
// ---------------------------------------------------------------------
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
if v == nil {
|
|
return
|
|
}
|
|
if err := json.NewEncoder(w).Encode(v); err != nil {
|
|
log.Printf("writeJSON error: %v", err)
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------
|
|
// health endpoint
|
|
// ---------------------------------------------------------------------
|
|
|
|
func handleHealthz(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{
|
|
"status": "ok",
|
|
"time": time.Now().Format(time.RFC3339),
|
|
})
|
|
}
|