-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(config): Add config Provider (#164)
Signed-off-by: Flc゛ <[email protected]>
- Loading branch information
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package config | ||
|
||
import "context" | ||
|
||
type configKey struct{} | ||
|
||
func NewContext[T any](ctx context.Context, config T) (context.Context, error) { | ||
return context.WithValue(ctx, configKey{}, config), nil | ||
} | ||
|
||
func FromContext[T any](ctx context.Context) (T, bool) { | ||
config, ok := ctx.Value(configKey{}).(T) | ||
return config, ok | ||
} | ||
|
||
func Provider[T any](config T) func(ctx context.Context) (context.Context, error) { | ||
return func(ctx context.Context) (context.Context, error) { | ||
return NewContext(ctx, config) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package config | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
type config struct { | ||
Host string | ||
Port int | ||
} | ||
|
||
type config2 struct { | ||
Host string | ||
Port int | ||
} | ||
|
||
func TestConfig(t *testing.T) { | ||
ctx, err := Provider(&config{ | ||
Host: "localhost", | ||
Port: 8080, | ||
})(context.Background()) | ||
assert.NoError(t, err) | ||
|
||
cfg, ok := FromContext[*config](ctx) | ||
assert.True(t, ok) | ||
assert.Equal(t, "localhost", cfg.Host) | ||
assert.Equal(t, 8080, cfg.Port) | ||
|
||
cfg2, ok := FromContext[*config2](ctx) | ||
assert.False(t, ok) | ||
assert.Nil(t, cfg2) | ||
} |