constant context keys

This commit is contained in:
Sergio Moura 2023-09-05 15:54:47 -04:00
parent a12b0e5f6f
commit ce6484f465

View File

@ -108,28 +108,34 @@ func OpenLocalSqliteDb() (*gorm.DB, error) {
type hishtoryContextKey string
const (
configCtxKey hishtoryContextKey = "config"
dbCtxKey hishtoryContextKey = "db"
homedirCtxKey hishtoryContextKey = "homedir"
)
func MakeContext() context.Context {
ctx := context.Background()
config, err := GetConfig()
if err != nil {
panic(fmt.Errorf("failed to retrieve config: %v", err))
}
ctx = context.WithValue(ctx, hishtoryContextKey("config"), config)
ctx = context.WithValue(ctx, configCtxKey, config)
db, err := OpenLocalSqliteDb()
if err != nil {
panic(fmt.Errorf("failed to open local DB: %v", err))
}
ctx = context.WithValue(ctx, hishtoryContextKey("db"), db)
ctx = context.WithValue(ctx, dbCtxKey, db)
homedir, err := os.UserHomeDir()
if err != nil {
panic(fmt.Errorf("failed to get homedir: %v", err))
}
ctx = context.WithValue(ctx, hishtoryContextKey("homedir"), homedir)
ctx = context.WithValue(ctx, homedirCtxKey, homedir)
return ctx
}
func GetConf(ctx context.Context) ClientConfig {
v := ctx.Value(hishtoryContextKey("config"))
v := ctx.Value(configCtxKey)
if v != nil {
return v.(ClientConfig)
}
@ -137,7 +143,7 @@ func GetConf(ctx context.Context) ClientConfig {
}
func GetDb(ctx context.Context) *gorm.DB {
v := ctx.Value(hishtoryContextKey("db"))
v := ctx.Value(dbCtxKey)
if v != nil {
return v.(*gorm.DB)
}
@ -145,7 +151,7 @@ func GetDb(ctx context.Context) *gorm.DB {
}
func GetHome(ctx context.Context) string {
v := ctx.Value(hishtoryContextKey("homedir"))
v := ctx.Value(homedirCtxKey)
if v != nil {
return v.(string)
}