feat: add X-Instance-Id header and instance_id log field

This commit is contained in:
kk10
2026-10-17 10:09:31 +03:00
parent cd6a1c7aee
commit dc79ef5e1f
4 changed files with 34 additions and 1 deletions
+2 -1
View File
@@ -27,7 +27,7 @@ func Run() error {
cfg := config.Load()
log := logger.New(cfg.Logging.Level)
log := logger.New(cfg.Logging.Level).With("instance_id", cfg.Server.InstanceID)
dbURL, err := cfg.Database.URL()
if err != nil {
@@ -80,6 +80,7 @@ func Run() error {
router := NewRouter(
log,
cfg.Server.InstanceID,
cfg.Server.MaxInflightRequests,
pool,
authService,
+2
View File
@@ -14,6 +14,7 @@ import (
func NewRouter(
log *slog.Logger,
instanceID string,
maxInflightRequests int,
db handler.Pinger,
authService *service.AuthService,
@@ -29,6 +30,7 @@ func NewRouter(
chatHandler := handler.NewChatHandler(chatService)
messageHandler := handler.NewMessageHandler(messageService)
router.Use(middleware.InstanceID(instanceID))
router.Use(middleware.RequestTimeout(5 * time.Second))
router.Use(middleware.RequestID)
router.Use(middleware.Logging(log))
+16
View File
@@ -32,6 +32,7 @@ type ServerConfig struct {
Port string
MaxInflightRequests int
SessionTTL time.Duration
InstanceID string
}
type LoggingConfig struct {
@@ -61,6 +62,7 @@ func Load() Config {
Port: getEnv("APP_PORT", "8080"),
MaxInflightRequests: getEnvNonNegativeInt("MAX_INFLIGHT_REQUESTS", 0),
SessionTTL: time.Duration(getEnvPositiveInt("SESSION_TTL_SECONDS", 3600)) * time.Second,
InstanceID: getInstanceID("INSTANCE_ID"),
},
Logging: LoggingConfig{
@@ -165,3 +167,17 @@ func getEnvSessionStore(key, def string) string {
return def
}
}
func getInstanceID(key string) string {
if v := os.Getenv(key); v != "" {
return v
}
host, err := os.Hostname()
if err != nil || host == "" {
log.Printf("cannot determine hostname, using \"unknown\" for %s: %v", key, err)
return "unknown"
}
return host
}
+14
View File
@@ -0,0 +1,14 @@
package middleware
import (
"net/http"
)
func InstanceID(id string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", id)
next.ServeHTTP(w, r)
})
}
}