58 lines
1.0 KiB
Go
58 lines
1.0 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/netip"
|
|
"time"
|
|
)
|
|
|
|
type requestContextKey struct{}
|
|
|
|
type RequestContext struct {
|
|
RequestID string
|
|
StartTime time.Time
|
|
Method string
|
|
Path string
|
|
ClientIp netip.Addr
|
|
UserAgent string
|
|
Referer string
|
|
}
|
|
|
|
func WithRequestContext(ctx context.Context, req *RequestContext) context.Context {
|
|
return context.WithValue(ctx, requestContextKey{}, req)
|
|
}
|
|
|
|
func GetRequestContext(ctx context.Context) *RequestContext {
|
|
v, ok := ctx.Value(requestContextKey{}).(*RequestContext)
|
|
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
return v
|
|
}
|
|
|
|
// ----------------------------------------------------------------------------------------
|
|
|
|
type userContextKey struct{}
|
|
|
|
type UserContext struct {
|
|
UserID int32
|
|
IsAdmin bool
|
|
TokenVersion int32
|
|
}
|
|
|
|
func WithUserContext(ctx context.Context, user *UserContext) context.Context {
|
|
return context.WithValue(ctx, userContextKey{}, user)
|
|
}
|
|
|
|
func GetUserContext(ctx context.Context) *UserContext {
|
|
v, ok := ctx.Value(userContextKey{}).(*UserContext)
|
|
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
return v
|
|
}
|