标签:说明 makefile conf Golan 了解 内容 rop inux 还需要
viper 是一个强大的golang 配置管理包,支持多种配置格式内容的读取,同时支持读取key/value 存储的数据
而且不只是读取内容 ,同时也包含了,配置的写入操作。
以下是一个简单的demo,同时使用docker 运行
项目使用go mod 进行包的管理
├── 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
启动
docker-compose up
效果
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,实际功能很强大,还需要再学习官方文档了解
https://github.com/spf13/viper
https://github.com/rongfengliang/viper-learning
标签:说明 makefile conf Golan 了解 内容 rop inux 还需要
原文地址:https://www.cnblogs.com/rongfengliang/p/11766356.html