Last active
February 27, 2020 19:29
-
-
Save wreulicke/1be53f10d8f967b9c6702b66363eb0c8 to your computer and use it in GitHub Desktop.
heetch/confitaのサンプル
This file contains hidden or 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
package config | |
import ( | |
"context" | |
"os" | |
"path/filepath" | |
"strings" | |
"github.com/heetch/confita" | |
"github.com/heetch/confita/backend" | |
"github.com/heetch/confita/backend/file" | |
) | |
type ServerConfig struct { | |
Port int `config:"port"` | |
} | |
// デフォルトのenv.Backendだと微妙だったので、コピペして持ってきてprefixをつけるようなbackendを自前で書いてる | |
func yataiboneEnvBackend() backend.Backend { | |
return backend.Func("yataibone-env", func(ctx context.Context, key string) ([]byte, error) { | |
if val := os.Getenv(key); val != "" { | |
return []byte(val), nil | |
} | |
key = strings.Replace(strings.ToUpper("YATAIBONE_"+key), "-", "_", -1) | |
if val := os.Getenv(key); val != "" { | |
return []byte(val), nil | |
} | |
return nil, backend.ErrNotFound | |
}) | |
} | |
func ReadServerConfig() (*ServerConfig, error) { | |
var bs []backend.Backend = []backend.Backend{ | |
file.NewOptionalBackend("/etc/yataibone/config.yml"), | |
} | |
if home, err := os.UserHomeDir(); err == nil { | |
bs = append(bs, file.NewOptionalBackend(filepath.Join(home, ".yataibone", "config.yml"))) | |
} | |
if wd, err := os.Getwd(); err == nil { | |
bs = append(bs, file.NewOptionalBackend(filepath.Join(wd, "yataibone.yml"))) | |
} | |
bs = append(bs, yataiboneEnvBackend()) | |
l := confita.NewLoader(bs...) | |
c := ServerConfig{ | |
Port: 8080, | |
} | |
err := l.Load(context.Background(), &c) | |
if err != nil { | |
return nil, err | |
} | |
return &c, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment