init
This commit is contained in:
76
core/appcontext/context.go
Normal file
76
core/appcontext/context.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package appcontext
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type customContextType string
|
||||
|
||||
const (
|
||||
AppCtx customContextType = "appCtx"
|
||||
)
|
||||
|
||||
type AppExtContext struct {
|
||||
UserEmail string // Email of the user
|
||||
RequestID string // RequestID - used to track logs across a request-response cycle
|
||||
Locale string // Locale for language
|
||||
Application string // application for dynamic application auth
|
||||
}
|
||||
|
||||
type AppContext struct {
|
||||
context.Context
|
||||
AppExtContext
|
||||
}
|
||||
|
||||
func GetAppCtx(ctx context.Context) (AppExtContext, bool) {
|
||||
if ctx == nil {
|
||||
return AppExtContext{}, false
|
||||
}
|
||||
appCtx, exists := ctx.Value(AppCtx).(AppExtContext)
|
||||
return appCtx, exists
|
||||
}
|
||||
|
||||
func WithAppCtx(ctx context.Context, appCtx AppExtContext) context.Context {
|
||||
return context.WithValue(ctx, AppCtx, appCtx)
|
||||
}
|
||||
|
||||
func UpgradeCtx(ctx context.Context) AppContext {
|
||||
var appCtx AppContext
|
||||
tCtx, _ := GetAppCtx(ctx)
|
||||
|
||||
appCtx.Context = ctx
|
||||
appCtx.AppExtContext = tCtx
|
||||
return appCtx
|
||||
}
|
||||
|
||||
func NewAppContext() AppContext {
|
||||
return AppContext{
|
||||
Context: context.Background(),
|
||||
AppExtContext: AppExtContext{},
|
||||
}
|
||||
}
|
||||
|
||||
func CopyAppContext(ctx context.Context) AppContext {
|
||||
appCtx, _ := GetAppCtx(ctx)
|
||||
return AppContext{
|
||||
Context: context.Background(),
|
||||
AppExtContext: appCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func New(id ...string) AppContext {
|
||||
var requestID string
|
||||
if len(id) > 0 {
|
||||
requestID = id[0]
|
||||
}
|
||||
if len(requestID) == 0 {
|
||||
requestID = strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
}
|
||||
appCtx := AppExtContext{
|
||||
RequestID: requestID,
|
||||
}
|
||||
ctx := UpgradeCtx(WithAppCtx(context.Background(), appCtx))
|
||||
return ctx
|
||||
}
|
||||
Reference in New Issue
Block a user