38 lines
1.4 KiB
Go
38 lines
1.4 KiB
Go
// Package httpserver exposes health and authenticated task-management endpoints.
|
|
package httpserver
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"git.yuntuo.hk/k2safe/orbit/pulse/service"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type Checker func(context.Context) error
|
|
|
|
func New(addr string, ready Checker, tasks ...*service.Service) *http.Server {
|
|
mux := http.NewServeMux()
|
|
write := func(w http.ResponseWriter, status int, body map[string]string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(body)
|
|
}
|
|
mux.HandleFunc("GET /health/live", func(w http.ResponseWriter, r *http.Request) {
|
|
write(w, http.StatusOK, map[string]string{"status": "alive"})
|
|
})
|
|
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
defer cancel()
|
|
if ready == nil || ready(ctx) != nil {
|
|
write(w, http.StatusServiceUnavailable, map[string]string{"status": "not_ready"})
|
|
return
|
|
}
|
|
write(w, http.StatusOK, map[string]string{"status": "ready", "scope": "database_and_schema"})
|
|
})
|
|
if len(tasks) > 0 && tasks[0] != nil {
|
|
registerTasks(mux, tasks[0])
|
|
}
|
|
return &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10}
|
|
}
|