-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboot.go
More file actions
71 lines (61 loc) · 1.8 KB
/
boot.go
File metadata and controls
71 lines (61 loc) · 1.8 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
package initd
import (
"context"
"fmt"
"log/slog"
"os"
"github.com/struct0x/envconfig"
)
// Boot is a minimal bootstrap handle created by [Minimal].
// It provides a context and loaded config, but no lifecycle management.
// Pass it to [WithBoot] when creating the full [App].
// Register cleanup hooks with [Boot.OnHandoff] — they run when [App.Run]
// starts, signaling the end of the bootstrap phase.
type Boot struct {
Logger *slog.Logger
ctx context.Context
cancel context.CancelFunc
closeFns []func()
}
// Context returns the bootstrap context. It is canceled when
// [App.Run] starts, signaling the end of the bootstrap phase.
func (b *Boot) Context() context.Context {
return b.ctx
}
// OnHandoff registers a function to run when the bootstrap phase ends
// (i.e. when [App.Run] is called). Use this to close temporary
// resources that were only needed during config loading.
func (b *Boot) OnHandoff(fn func()) {
b.closeFns = append(b.closeFns, fn)
}
// close cancels the boot context and runs all OnHandoff hooks.
func (b *Boot) close() {
b.cancel()
for _, fn := range b.closeFns {
fn()
}
}
// Minimal loads config from environment variables and returns a [Boot]
// handle. Use this when dependencies needed during config loading
// (e.g. a secret store client) must exist before [New].
func Minimal[C any](cfg *C, opts ...Option) (*Boot, error) {
ac := appConfig{}
for _, o := range opts {
o(&ac)
}
if !ac.skipEnvLoad {
lookups := ac.envLookups
if len(lookups) == 0 {
lookups = []envconfig.LookupEnv{os.LookupEnv}
}
if err := envconfig.Read(cfg, lookups...); err != nil {
return nil, fmt.Errorf("initd: %w", err)
}
}
ctx, cancel := context.WithCancel(context.Background())
return &Boot{
Logger: newLogger(&ac).WithGroup("boot"),
ctx: ctx,
cancel: cancel,
}, nil
}