viper 是一個強大的golang 配置管理包,支持多種配置格式內容的讀取,同時支持讀取key/value 存儲的數據
並且不僅是讀取內容 ,同時也包含了,配置的寫入操做。
如下是一個簡單的demo,同時使用docker 運行linux
項目使用go mod 進行包的管理git
├── Dockerfile
├── Makefile
├── README.md
├── cmd
│ └── yaml
│ └── main.go
├── docker-compose.yaml
├── go.mod
└── go.sum
module github.com/rongfengliang/viper-app
go 1.13
require github.com/spf13/viper v1.4.0
package main
import (
"bytes"
"log"
"github.com/spf13/viper"
)
func main() {
viper.SetConfigType("yaml")
var yamlExample = []byte(`
Hacker: true
name: steve
hobbies:
- skateboarding
- snowboarding
- go
clothing:
- jacket: leather
- trousers: denim
age: 35
eyes: brown
beard: true
`)
viper.AutomaticEnv()
if err := viper.ReadConfig(bytes.NewBuffer(yamlExample)); err != nil {
log.Fatal("some error", err)
}
log.Print(viper.GetString("name"))
viper.Set("name", "demoapp rong")
log.Print(viper.GetString("name"))
var appname string = viper.GetString("APIKEY")
log.Print(appname)
}
build-app: clean make-dir build-mac build-linux build-windows
clean:
rm -rf build/*
make-dir:
mkdir -p build/{mac,linux,windows}
build-mac:
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o build/mac ./cmd/...
build-linux:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/linux ./cmd/...
build-windows:
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o build/windows ./cmd/...
FROM alpine
LABEL EMAIL="1141591465@qq.com"
LABEL AUTHOR="dalongrong"
WORKDIR /app
COPY build/linux/yaml /app/yaml
RUN chmod +x /app/yaml
CMD [ "./yaml" ]
version: "3"
services:
app:
build: ./
image: dalongrong/viper-app
env_file:
- .env
不包含環境變量的
go run cmd/yam/main.go
支持環境變量的
APIKEY=rongfengliang go run cmd/yaml/main.go
docker-compose build
啓動github
docker-compose up
效果golang
Attaching to viper-golang_app_1
app_1 | 2019/10/30 08:56:31 steve
app_1 | 2019/10/30 08:56:31 demoapp rong
app_1 | 2019/10/30 08:56:31 rongfengliang
viper-golang_app_1 exited with code 0
以上是一個簡單的demo,實際功能很強大,還須要再學習官方文檔瞭解docker
https://github.com/spf13/viper
https://github.com/rongfengliang/viper-learningwindows