Files
mtusi2026lab4/internal/transport/rest/instance.go
T
2026-10-21 21:22:42 +03:00

68 lines
1.6 KiB
Go

package rest
import (
"net/http"
"os"
)
const (
instanceIDEnv = "INSTANCE_ID"
instanceIDHeader = "X-Instance-Id"
)
// InstanceID is the alias of this API process reported in the X-Instance-Id
// response header (contract 1.3.0). INSTANCE_ID wins when set; otherwise the
// hostname is used, which inside a container is the short container id the
// stand maps back to the replica that served the request.
func InstanceID() string {
if id := os.Getenv(instanceIDEnv); id != "" {
return id
}
if host, err := os.Hostname(); err == nil && host != "" {
return host
}
return "unknown"
}
// instanceIDWriter injects the header on the first write of the response, so
// every API-generated response carries it — including errors produced by the
// router, the security handler and the error handler rather than by a handler.
// A value already set by the transport is never overwritten.
type instanceIDWriter struct {
http.ResponseWriter
id string
sealed bool
}
func (w *instanceIDWriter) inject() {
if w.sealed {
return
}
w.sealed = true
if w.Header().Get(instanceIDHeader) == "" {
w.Header().Set(instanceIDHeader, w.id)
}
}
func (w *instanceIDWriter) WriteHeader(status int) {
w.inject()
w.ResponseWriter.WriteHeader(status)
}
func (w *instanceIDWriter) Write(body []byte) (int, error) {
w.inject()
return w.ResponseWriter.Write(body)
}
func instanceIDMiddleware(id string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(&instanceIDWriter{ResponseWriter: w, id: id}, r)
})
}