generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
config.go
59 lines (50 loc) 路 1.46 KB
/
config.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
59
package ftl
import (
"context"
"fmt"
"runtime"
"strings"
"github.com/TBD54566975/ftl/internal/modulecontext"
)
// ConfigType is a type that can be used as a configuration value.
type ConfigType interface{ any }
// Config declares a typed configuration key for the current module.
func Config[T ConfigType](name string) ConfigValue[T] {
module := callerModule()
return ConfigValue[T]{Ref{module, name}}
}
// ConfigValue is a typed configuration key for the current module.
type ConfigValue[T ConfigType] struct {
Ref
}
func (c ConfigValue[T]) String() string { return fmt.Sprintf("config \"%s\"", c.Ref) }
func (c ConfigValue[T]) GoString() string {
var t T
return fmt.Sprintf("ftl.ConfigValue[%T](\"%s\")", t, c.Ref)
}
// Get returns the value of the configuration key from FTL.
func (c ConfigValue[T]) Get(ctx context.Context) (out T) {
err := modulecontext.FromContext(ctx).GetConfig(c.Name, &out)
if err != nil {
panic(fmt.Errorf("failed to get %s: %w", c, err))
}
return
}
func callerModule() string {
pc, _, _, ok := runtime.Caller(2)
if !ok {
panic("failed to get caller")
}
details := runtime.FuncForPC(pc)
if details == nil {
panic("failed to get caller")
}
module := details.Name()
if strings.HasPrefix(module, "github.com/TBD54566975/ftl/go-runtime/ftl") {
return "testing"
}
if !strings.HasPrefix(module, "ftl/") {
panic("must be called from an FTL module not " + module)
}
return strings.Split(strings.Split(module, "/")[1], ".")[0]
}