Download internal/reqlog/context.go from a3216/ds2api: direct link, hf CLI and curl.
- Browser
- Download file 2 kB
-
https://huggingface.co/spaces/a3216/ds2api/resolve/main/internal/reqlog/context.go
- Command line
-
hf download hf://spaces/a3216/ds2api/internal/reqlog/context.go
-
curl -L -o context.go https://huggingface.co/spaces/a3216/ds2api/resolve/main/internal/reqlog/context.go
2 kB
| package reqlog | |
| import ( | |
| "context" | |
| "strings" | |
| "sync" | |
| ) | |
| type ctxKey struct{} | |
| // Record 是中间件挂在 request context 上的可变记录,业务代码可补充字段。 | |
| type Record struct { | |
| mu sync.Mutex | |
| e Entry | |
| } | |
| func WithRecord(ctx context.Context, rec *Record) context.Context { | |
| return context.WithValue(ctx, ctxKey{}, rec) | |
| } | |
| func FromContext(ctx context.Context) *Record { | |
| if ctx == nil { | |
| return nil | |
| } | |
| rec, _ := ctx.Value(ctxKey{}).(*Record) | |
| return rec | |
| } | |
| func (r *Record) set(fn func(*Entry)) { | |
| if r == nil { | |
| return | |
| } | |
| r.mu.Lock() | |
| fn(&r.e) | |
| r.mu.Unlock() | |
| } | |
| // Snapshot 返回当前记录的副本。 | |
| func (r *Record) Snapshot() Entry { | |
| if r == nil { | |
| return Entry{} | |
| } | |
| r.mu.Lock() | |
| defer r.mu.Unlock() | |
| return r.e | |
| } | |
| func SetAPIKey(ctx context.Context, name, masked string) { | |
| FromContext(ctx).set(func(e *Entry) { | |
| if name != "" { | |
| e.APIKeyName = name | |
| } | |
| if masked != "" { | |
| e.APIKey = masked | |
| } | |
| }) | |
| } | |
| func SetAccount(ctx context.Context, account string) { | |
| FromContext(ctx).set(func(e *Entry) { e.Account = account }) | |
| } | |
| func SetModel(ctx context.Context, model string) { | |
| FromContext(ctx).set(func(e *Entry) { e.Model = model }) | |
| } | |
| func SetStream(ctx context.Context, stream bool) { | |
| FromContext(ctx).set(func(e *Entry) { e.Stream = stream }) | |
| } | |
| func SetErrorCode(ctx context.Context, code, message string) { | |
| FromContext(ctx).set(func(e *Entry) { | |
| if code != "" { | |
| e.ErrorCode = code | |
| } | |
| if message != "" { | |
| e.Error = truncate(message, 500) | |
| } | |
| }) | |
| } | |
| func SetUpstream(ctx context.Context, detail string) { | |
| FromContext(ctx).set(func(e *Entry) { e.Upstream = truncate(detail, 500) }) | |
| } | |
| func truncate(s string, max int) string { | |
| s = strings.TrimSpace(s) | |
| if len(s) <= max { | |
| return s | |
| } | |
| return s[:max] + "..." | |
| } | |
| // MaskKey 只保留密钥前 6 位,避免日志泄露完整凭证。 | |
| func MaskKey(key string) string { | |
| key = strings.TrimSpace(key) | |
| if key == "" { | |
| return "" | |
| } | |
| if len(key) <= 6 { | |
| return "***" | |
| } | |
| return key[:6] + "***" | |
| } | |