51 lines
1.4 KiB
Go
51 lines
1.4 KiB
Go
package platform
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type HTTPApp struct {
|
|
DB *pgxpool.Pool
|
|
Mux *http.ServeMux
|
|
}
|
|
|
|
func NewHTTPApp(db *pgxpool.Pool) *HTTPApp {
|
|
app := &HTTPApp{DB: db, Mux: http.NewServeMux()}
|
|
app.Mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "service": "bell", "time": time.Now().UTC()})
|
|
})
|
|
app.Mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
|
|
if err := db.Ping(r.Context()); err != nil {
|
|
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "not_ready"})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ready"})
|
|
})
|
|
return app
|
|
}
|
|
|
|
func (a *HTTPApp) Router() *http.ServeMux { return a.Mux }
|
|
|
|
func (a *HTTPApp) Handler() http.Handler {
|
|
return securityHeaders(a.Mux)
|
|
}
|
|
|
|
func securityHeaders(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("X-Frame-Options", "DENY")
|
|
w.Header().Set("Referrer-Policy", "no-referrer")
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|