Files
geo/server/internal/shared/config/runtime/env/env.go
T

63 lines
1.3 KiB
Go
Raw Normal View History

// Package env is adapted from go-kratos/kratos config/env.
//
// Upstream: https://github.com/go-kratos/kratos/tree/v2.9.2/config/env
// License: MIT, see ../LICENSE.kratos.
package env
import (
"os"
"strings"
"github.com/geo-platform/tenant-api/internal/shared/config/runtime"
)
type env struct {
prefixes []string
}
func NewSource(prefixes ...string) runtime.Source {
return &env{prefixes: prefixes}
}
func (e *env) Load() ([]*runtime.KeyValue, error) {
return e.load(os.Environ()), nil
}
func (e *env) load(envs []string) []*runtime.KeyValue {
kvs := make([]*runtime.KeyValue, 0, len(envs))
for _, item := range envs {
key, value, _ := strings.Cut(item, "=")
if key == "" {
continue
}
if len(e.prefixes) > 0 {
prefix, ok := matchPrefix(e.prefixes, key)
if !ok || key == prefix {
continue
}
key = strings.TrimPrefix(key, prefix)
key = strings.TrimPrefix(key, "_")
}
if key != "" {
kvs = append(kvs, &runtime.KeyValue{
Key: key,
Value: []byte(value),
})
}
}
return kvs
}
func (e *env) Watch() (runtime.Watcher, error) {
return NewWatcher()
}
func matchPrefix(prefixes []string, s string) (string, bool) {
for _, p := range prefixes {
if strings.HasPrefix(s, p) {
return p, true
}
}
return "", false
}