mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-05-08 22:56:55 +08:00
- Introduced reusable utilities in `requestmeta` to manage endpoint and response status in request contexts. - Refactored plugins and handlers to use context-based metadata, removing direct dependency on `gin`. - Updated tests to validate new context utilities and replaced `gin`-based context handling. Fixed: #3166
63 lines
1.3 KiB
Go
63 lines
1.3 KiB
Go
package logging
|
|
|
|
import (
|
|
"context"
|
|
"sync/atomic"
|
|
)
|
|
|
|
type endpointKey struct{}
|
|
type responseStatusKey struct{}
|
|
|
|
type responseStatusHolder struct {
|
|
status atomic.Int32
|
|
}
|
|
|
|
func WithEndpoint(ctx context.Context, endpoint string) context.Context {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
return context.WithValue(ctx, endpointKey{}, endpoint)
|
|
}
|
|
|
|
func GetEndpoint(ctx context.Context) string {
|
|
if ctx == nil {
|
|
return ""
|
|
}
|
|
if endpoint, ok := ctx.Value(endpointKey{}).(string); ok {
|
|
return endpoint
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func WithResponseStatusHolder(ctx context.Context) context.Context {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
if holder, ok := ctx.Value(responseStatusKey{}).(*responseStatusHolder); ok && holder != nil {
|
|
return ctx
|
|
}
|
|
return context.WithValue(ctx, responseStatusKey{}, &responseStatusHolder{})
|
|
}
|
|
|
|
func SetResponseStatus(ctx context.Context, status int) {
|
|
if ctx == nil || status <= 0 {
|
|
return
|
|
}
|
|
holder, ok := ctx.Value(responseStatusKey{}).(*responseStatusHolder)
|
|
if !ok || holder == nil {
|
|
return
|
|
}
|
|
holder.status.Store(int32(status))
|
|
}
|
|
|
|
func GetResponseStatus(ctx context.Context) int {
|
|
if ctx == nil {
|
|
return 0
|
|
}
|
|
holder, ok := ctx.Value(responseStatusKey{}).(*responseStatusHolder)
|
|
if !ok || holder == nil {
|
|
return 0
|
|
}
|
|
return int(holder.status.Load())
|
|
}
|