Golang實現yaml配置檔案的載入
阿新 • • 發佈:2022-04-22
配置檔案載入
yaml檔案
yaml中一部分程式碼
# catering Global Configuration # jwt configuration jwt: signing-key: 'catering' expires-time: 604800 issuer: 'catering' # zap logger configuration zap: level: 'info' format: 'console' prefix: '[catering]' director: 'log' show-line: true encode-level: 'LowercaseColorLevelEncoder' stacktrace-key: 'stacktrace' log-in-console: true # redis configuration redis: db: 0 addr: '192.168.138.128:6379' password: '' # casbin configuration casbin: model-path: './resource/rbac_model.conf' # system configuration system: env: 'develop' # Change to "develop" to skip authentication for development mode addr: 8888 db-type: 'mysql' oss-type: 'local' # 控制oss選擇走本地還是 七牛等其他倉 自行增加其他oss倉可以在 server/utils/upload/upload.go 中 NewOss函式配置 use-multipoint: false # IP限制次數 一個小時15000次 iplimit-count: 15000 # IP限制一個小時 iplimit-time: 3600 # captcha configuration captcha: key-long: 6 img-width: 240 img-height: 80 # mysql connect configuration mysql: host: 127.0.0.1 port: "3306" config: charset=utf8mb4&parseTime=True&loc=Local db-name: gva username: root password: root max-idle-conns: 0 max-open-conns: 0 log-mode: "" log-zap: false
配置檔案結構體
結構體中一部分程式碼
package config
type JWT struct {
SigningKey string `json:"signingKey" yaml:"signing-key"` // jwt簽名
ExpiresTime int64 `json:"expiresTime" yaml:"expires-time"` // 過期時間
Issuer string `json:"issuer" yaml:"issuer"` // 簽發者
}
package config type Config struct { JWT JWT `json:"jwt" yaml:"jwt"` Zap Zap `json:"zap" yaml:"zap"` Redis Redis `json:"redis" yaml:"redis"` Casbin Casbin `json:"casbin" yaml:"casbin"` System System `json:"system" yaml:"system"` Captcha Captcha `json:"captcha" yaml:"captcha"` // gorm Mysql Mysql `json:"mysql" yaml:"mysql"` // oss Local Local `json:"local" yaml:"local"` AliyunOSS AliyunOSS `json:"aliyunOSS" yaml:"aliyun-oss"` Excel Excel `json:"excel" yaml:"excel"` // 跨域配置 Cors CORS `json:"cors" yaml:"cors"` }
初始化檔案
package initialize import ( "catering/global" "io/ioutil" "gopkg.in/yaml.v2" ) func InitConfig() error { path := "./conf/config.yaml" data, err := ioutil.ReadFile(path) if err != nil { return err } //yaml.Unmarshal會根據yaml標籤的欄位進行賦值 err = yaml.Unmarshal(data, &global.Config) if err != nil { return err } return nil }