58 lines
940 B
Go
58 lines
940 B
Go
package appctx
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
|
|
"wucher/internal/shared/pkg/uuidv7"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const userIDKey contextKey = "appctx-user-id"
|
|
|
|
func WithUserID(ctx context.Context, userID []byte) context.Context {
|
|
if len(userID) == 0 {
|
|
return ctx
|
|
}
|
|
|
|
copyID := make([]byte, len(userID))
|
|
copy(copyID, userID)
|
|
return context.WithValue(ctx, userIDKey, copyID)
|
|
}
|
|
|
|
func GetUserID(ctx context.Context) []byte {
|
|
if ctx == nil {
|
|
return nil
|
|
}
|
|
|
|
raw := ctx.Value(userIDKey)
|
|
if raw == nil {
|
|
if getter, ok := any(ctx).(interface{ UserValue(any) any }); ok {
|
|
raw = getter.UserValue("user_id")
|
|
}
|
|
}
|
|
|
|
switch v := raw.(type) {
|
|
case []byte:
|
|
if len(v) == 0 {
|
|
return nil
|
|
}
|
|
out := make([]byte, len(v))
|
|
copy(out, v)
|
|
return out
|
|
case string:
|
|
s := strings.TrimSpace(v)
|
|
if s == "" {
|
|
return nil
|
|
}
|
|
id, err := uuidv7.ParseString(s)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return id
|
|
default:
|
|
return nil
|
|
}
|
|
}
|