Replace string context keys with typed constants

This commit is contained in:
dwrz
2026-06-09 23:28:29 +00:00
parent c158283f3d
commit 495c89de0e

View File

@@ -33,6 +33,15 @@ import (
openai "github.com/sashabaranov/go-openai"
)
// Context keys for request-scoped values.
type key string
const (
logKey key = "log"
idKey key = "id"
ipKey key = "ip"
)
//go:embed all:static/*
var static embed.FS
@@ -189,9 +198,9 @@ func (svc *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Enrich context with request-scoped values.
ctx := r.Context()
ctx = context.WithValue(ctx, "log", log)
ctx = context.WithValue(ctx, "id", id)
ctx = context.WithValue(ctx, "ip", ip)
ctx = context.WithValue(ctx, logKey, log)
ctx = context.WithValue(ctx, idKey, id)
ctx = context.WithValue(ctx, ipKey, ip)
r = r.WithContext(ctx)
log.InfoContext(ctx, "handling")
@@ -346,7 +355,7 @@ func (svc *Service) JobCount() int {
func (svc *Service) home(w http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
log = ctx.Value("log").(*slog.Logger)
log = ctx.Value(logKey).(*slog.Logger)
)
if r.URL.Path != "/" {
@@ -408,7 +417,7 @@ type Response struct {
func (svc *Service) voice(w http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
log = ctx.Value("log").(*slog.Logger)
log = ctx.Value(logKey).(*slog.Logger)
)
// Parse request.
@@ -619,7 +628,7 @@ type StreamMessage struct {
func (svc *Service) voiceStream(w http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
log = ctx.Value("log").(*slog.Logger)
log = ctx.Value(logKey).(*slog.Logger)
)
// Check that the response writer supports flushing.
@@ -848,7 +857,7 @@ func (svc *Service) voiceStream(w http.ResponseWriter, r *http.Request) {
func (svc *Service) models(w http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
log = ctx.Value("log").(*slog.Logger)
log = ctx.Value(logKey).(*slog.Logger)
)
models, err := svc.llm.ListModels(ctx)
@@ -886,7 +895,7 @@ func (svc *Service) models(w http.ResponseWriter, r *http.Request) {
func (svc *Service) voices(w http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
log = ctx.Value("log").(*slog.Logger)
log = ctx.Value(logKey).(*slog.Logger)
)
voices, err := svc.tts.ListVoices(ctx)