Skip to content

Commit

Permalink
feat(config): Add config Provider (#164)
Browse files Browse the repository at this point in the history
Signed-off-by: Flc゛ <[email protected]>
  • Loading branch information
flc1125 authored Mar 17, 2024
1 parent 9bbdf04 commit eb5300c
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
20 changes: 20 additions & 0 deletions config/config.go
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)
}
}
35 changes: 35 additions & 0 deletions config/config_test.go
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)
}

0 comments on commit eb5300c

Please sign in to comment.