1个人blog网站
一直想开发一个属于自己的Blog,以前也尝试开发,但是后来就不了了之了,现在终于来了,这次把开发过程给记录下来。同时记录开发过程中的问题。加油吧!😊
第一篇主要就是项目结构搭建和读取配置文件
注意:项目结构后期可能会更新
😊1.1 项目结构搭建
😊1.2 配置文件读取
读取配置文件主要是使用Viper
viper地址
- conf.yaml
# server
# AppMode :dev or release
server:
app-mode: dev
http-port: :11111
ip: 0.0.0.0
# mysql
db:
host: 127.0.0.1
port: 3306
user: root
pwd: 123456
name: smart_blog
# 日志
log:
file-name: ./log/log.txt
max-size: 10
max-backups: 5
max-age: 30
compress: false
encoder: console
level: -1 # -1 debug, 0 info, 3 error
output-console: true
- conf.go
package conf
type Conf struct {
Server Server `json:"server" yaml:"server"`
DB DB `json:"db" yaml:"db"`
Log Log `json:"log" yaml:"log"`
}
type Server struct {
AppMode string `mapstructure:"app-mode" json:"app-mode" yaml:"app-mode"`
HttpPort string `mapstructure:"http-port" json:"http-port" yaml:"http-port"`
IP string `json:"ip" yaml:"ip"`
}
type DB struct {
Host string `json:"host" yaml:"host"`
Port string `json:"port" yaml:"port"`
User string `json:"user" yaml:"user"`
Pwd string `json:"pwd" yaml:"pwd"`
Name string `json:"name" yaml:"name"`
}
type Log struct {
FileName string `mapstructure:"file-name" json:"file-name" yaml:"file-name"`
MaxSize int `mapstructure:"max-size" json:"max-size" yaml:"max-size"`
MaxBackups int `mapstructure:"max-backups" json:"max-backups" yaml:"max-backups"`
MaxAge int `mapstructure:"max-age" json:"max-age" yaml:"max-age"`
Compress bool `mapstructure:"compress json:"compress" yaml:"compress"`
Encoder string `mapstructure:"encoder" json:"encoder" yaml:"encoder"`
Level int8 `mapstructure:"level" json:"level" yaml:"level"`
OutputConsole bool `mapstructure:"output-console" json:"output-console" yaml:"output-console"`
}
- global.go
package global
import "daily-blog/conf"
var (
GVA_CONFIG conf.Conf
)
- init-conf.go
package global
import (
"fmt"
"log"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
func InitConf() {
viper.SetConfigFile("./conf/conf.yaml")
err := viper.ReadInConfig()
if err != nil {
log.Panic("日志文件读取失败", err)
return
}
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
if err = viper.Unmarshal(&GVA_CONFIG); err != nil {
fmt.Println(err)
}
})
if err = viper.Unmarshal(&GVA_CONFIG); err != nil {
fmt.Println(err)
}
}
- main.go
func main() {
global.InitConf()
fmt.Printf("%+v\n", global.GVA_CONFIG)
}
执行一下:
😊读取配置文件时踩坑
对于配置文件某一个字段是多个单词组合成的,使用 -
或者 _
分割,给对应结构体指定Tag时,也需要使用 -
或者 _
分割,发现Viper对于这种字段解析不到结构体上
解决方案L: 给对应的字段上添加上 tag mapstructure:"xxx-xxx"
举个例子:
解析上了
如果不加mapstructure就会解析不到。
至于什么原因,没有深究,先挖个坑吧。