-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
58 lines (47 loc) · 1.61 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package soba
import (
"context"
"os"
"github.com/pkg/errors"
)
// ctxKey is a subtype for context keys.
type ctxKey struct{}
// hCtxKey is a context key used to store handler in context values.
var hCtxKey = &ctxKey{}
// Load returns a new context with a soba instance. It relies on conventions and default configurations:
// - First, it will lookup from environment variable if a configuration path is defined.
// - Then, it will lookup from current directory if a configuration file exists.
// - Finally, it will create a new instance with default configurations.
//
// For specific configurations, please uses either LoadWithConfig or LoadWithFile.
func Load(ctx context.Context) (context.Context, error) {
path := os.Getenv(EnvConfigPath)
if path != "" && CheckPath(path) {
return LoadWithFile(ctx, path)
}
if CheckPath(DefaultConfigPath) {
return LoadWithFile(ctx, DefaultConfigPath)
}
return LoadWithConfig(ctx, NewDefaultConfig())
}
// LoadWithConfig returns a new context with a soba instance using given configuration.
func LoadWithConfig(ctx context.Context, config *Config) (context.Context, error) {
err := ValidateConfig(config)
if err != nil {
return ctx, errors.Wrap(err, "configuration is invalid")
}
handler, err := create(config)
if err != nil {
return ctx, err
}
ctx = context.WithValue(ctx, hCtxKey, handler)
return ctx, nil
}
// LoadWithFile returns a new context with a soba instance using given file path.
func LoadWithFile(ctx context.Context, path string) (context.Context, error) {
conf, err := ParseConfig(path)
if err != nil {
return ctx, err
}
return LoadWithConfig(ctx, conf)
}