forked from mtusi2026/mtusi2026lab7
35 lines
788 B
Go
35 lines
788 B
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
"sync/atomic"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// Docker's hostname lets the operator map an API response to its container.
|
|
var instanceID = func() string {
|
|
id, err := os.Hostname()
|
|
if err != nil || id == "" {
|
|
return uuid.NewString()
|
|
}
|
|
return id
|
|
}()
|
|
|
|
var draining atomic.Bool
|
|
|
|
func BeginShutdown() { draining.Store(true) }
|
|
|
|
func withInstance(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("X-Instance-Id", instanceID)
|
|
w.Header().Set("X-Request-Id", newRequestID())
|
|
if draining.Load() && r.URL.Path != "/health/live" {
|
|
writeError(w, 503, "unavailable", "instance is shutting down", w.Header().Get("X-Request-Id"))
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|