go语言web开发系列之四:gin框架用viper读取配置文件数据

一,安装viper

1,viper的代码地址:

https://github.com/spf13/viper

查看viper版本:

https://github.com/spf13/viper/releases

2,安装:

root@ku:~# go get -u github.com/spf13/viper@v1.7.1

说明:刘宏缔的go森林是一个专注golang的博客,
          地址:https://blog.csdn.net/weixin_43881017

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,演示项目的相关信息

1,项目地址:

https://github.com/liuhongdi/digv04

2,功能说明:

    能从配置文件中读取数据库等相关的配置

3,项目结构:如图:

三,go代码说明

1,config/config.yaml

  1.  
    Database:
  2.  
    DBType: mysql
  3.  
    UserName: root
  4.  
    Password: password
  5.  
    Host: 127.0.0.1:3306
  6.  
    DBName: dig
  7.  
    Charset: utf8
  8.  
    ParseTime: True
  9.  
    MaxIdleConns: 10
  10.  
    MaxOpenConns: 30
  11.  
    Server:
  12.  
    RunMode: debug
  13.  
    HttpPort: 8000
  14.  
    ReadTimeout: 60
  15.  
    WriteTimeout: 60

2,global/setting.go

  1.  
    package global
  2.  
     
  3.  
    import (
  4.  
    "fmt"
  5.  
    "github.com/liuhongdi/digv04/pkg/setting"
  6.  
    "time"
  7.  
    )
  8.  
    //服务器配置
  9.  
    type ServerSettingS struct {
  10.  
    RunMode string
  11.  
    HttpPort string
  12.  
    ReadTimeout time.Duration
  13.  
    WriteTimeout time.Duration
  14.  
    }
  15.  
    //数据库配置
  16.  
    type DatabaseSettingS struct {
  17.  
    DBType string
  18.  
    UserName string
  19.  
    Password string
  20.  
    Host string
  21.  
    DBName string
  22.  
    Charset string
  23.  
    ParseTime bool
  24.  
    MaxIdleConns int
  25.  
    MaxOpenConns int
  26.  
    }
  27.  
    //定义全局变量
  28.  
    var (
  29.  
    ServerSetting *ServerSettingS
  30.  
    DatabaseSetting *DatabaseSettingS
  31.  
    )
  32.  
     
  33.  
    //读取配置到全局变量
  34.  
    func SetupSetting() error {
  35.  
    s, err := setting.NewSetting()
  36.  
    if err != nil {
  37.  
    return err
  38.  
    }
  39.  
    err = s.ReadSection("Database", &DatabaseSetting)
  40.  
    if err != nil {
  41.  
    return err
  42.  
    }
  43.  
     
  44.  
    err = s.ReadSection("Server", &ServerSetting)
  45.  
    if err != nil {
  46.  
    return err
  47.  
    }
  48.  
     
  49.  
    fmt.Println("setting:")
  50.  
    fmt.Println(ServerSetting)
  51.  
    fmt.Println(DatabaseSetting)
  52.  
    return nil
  53.  
    }

3,global/db.go

  1.  
    package global
  2.  
     
  3.  
    import (
  4.  
    "fmt"
  5.  
    "github.com/jinzhu/gorm"
  6.  
    )
  7.  
     
  8.  
    var (
  9.  
    DBLink *gorm.DB
  10.  
    )
  11.  
    //建立数据库连接,配置从配置文件中获取
  12.  
    func SetupDBLink() (error) {
  13.  
    var err error
  14.  
    DBLink, err = gorm.Open(DatabaseSetting.DBType,
  15.  
    fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local",
  16.  
    DatabaseSetting.UserName,
  17.  
    DatabaseSetting.Password,
  18.  
    DatabaseSetting.Host,
  19.  
    DatabaseSetting.DBName,
  20.  
    DatabaseSetting.Charset,
  21.  
    DatabaseSetting.ParseTime,
  22.  
    ))
  23.  
    if err != nil {
  24.  
    return err
  25.  
    }
  26.  
     
  27.  
    if ServerSetting.RunMode == "debug" {
  28.  
    DBLink.LogMode(true)
  29.  
    }
  30.  
    DBLink.SingularTable(true)
  31.  
    DBLink.DB().SetMaxIdleConns(DatabaseSetting.MaxIdleConns)
  32.  
    DBLink.DB().SetMaxOpenConns(DatabaseSetting.MaxOpenConns)
  33.  
    return nil
  34.  
    }

4,pkg/setting/setting.go

  1.  
    package setting
  2.  
     
  3.  
    import (
  4.  
    "github.com/spf13/viper"
  5.  
    )
  6.  
     
  7.  
    type Setting struct {
  8.  
    vp *viper.Viper
  9.  
    }
  10.  
     
  11.  
    var sections = make(map[string]interface{})
  12.  
     
  13.  
    //读取配置
  14.  
    func NewSetting() (*Setting, error) {
  15.  
    vp := viper.New()
  16.  
    vp.SetConfigName("config")
  17.  
    vp.AddConfigPath("config")
  18.  
    vp.SetConfigType("yaml")
  19.  
    err := vp.ReadInConfig()
  20.  
    if err != nil {
  21.  
    return nil, err
  22.  
    }
  23.  
     
  24.  
    s := &Setting{vp}
  25.  
    return s, nil
  26.  
    }
  27.  
     
  28.  
    //读取指定的一段
  29.  
    func (s *Setting) ReadSection(k string, v interface{}) error {
  30.  
    err := s.vp.UnmarshalKey(k, v)
  31.  
    if err != nil {
  32.  
    return err
  33.  
    }
  34.  
     
  35.  
    if _, ok := sections[k]; !ok {
  36.  
    sections[k] = v
  37.  
    }
  38.  
    return nil
  39.  
    }
  40.  
     
  41.  
    //重新加载
  42.  
    func (s *Setting) ReloadAllSection() error {
  43.  
    for k, v := range sections {
  44.  
    err := s.ReadSection(k, v)
  45.  
    if err != nil {
  46.  
    return err
  47.  
    }
  48.  
    }
  49.  
     
  50.  
    return nil
  51.  
    }

5,main.go

  1.  
    package main
  2.  
     
  3.  
    import (
  4.  
    "github.com/gin-gonic/gin"
  5.  
    _ "github.com/jinzhu/gorm/dialects/mysql"
  6.  
    "github.com/liuhongdi/digv04/global"
  7.  
    "github.com/liuhongdi/digv04/router"
  8.  
    "log"
  9.  
    )
  10.  
     
  11.  
    //init
  12.  
    func init() {
  13.  
    err := global.SetupSetting()
  14.  
    if err != nil {
  15.  
    log.Fatalf("init.setupSetting err: %v", err)
  16.  
    }
  17.  
     
  18.  
    err = global.SetupDBLink()
  19.  
    if err != nil {
  20.  
    log.Fatalf("init.setupDBEngine err: %v", err)
  21.  
    }
  22.  
    }
  23.  
     
  24.  
    func main() {
  25.  
    //设置运行模式
  26.  
    gin.SetMode(global.ServerSetting.RunMode)
  27.  
    //引入路由
  28.  
    r := router.Router()
  29.  
    //run
  30.  
    r.Run(":"+global.ServerSetting.HttpPort)
  31.  
    }

6,其他代码可访问github获取

四,测试效果

1,访问:

http://127.0.0.1:8000/article/getone/1

返回:

说明数据库可以正常连接,端口号也因为配置文件的设置改变成了8000

五,查看库的版本:

  1.  
    module github.com/liuhongdi/digv04
  2.  
     
  3.  
    go 1.15
  4.  
     
  5.  
    require (
  6.  
    github.com/gin-gonic/gin v1.6.3
  7.  
    github.com/go-playground/universal-translator v0.17.0
  8.  
    github.com/go-playground/validator/v10 v10.2.0
  9.  
    github.com/jinzhu/gorm v1.9.16
  10.  
    github.com/magiconair/properties v1.8.4 // indirect
  11.  
    github.com/mitchellh/mapstructure v1.3.3 // indirect
  12.  
    github.com/pelletier/go-toml v1.8.1 // indirect
  13.  
    github.com/spf13/afero v1.4.1 // indirect
  14.  
    github.com/spf13/cast v1.3.1 // indirect
  15.  
    github.com/spf13/jwalterweatherman v1.1.0 // indirect
  16.  
    github.com/spf13/pflag v1.0.5 // indirect
  17.  
    github.com/spf13/viper v1.7.1
  18.  
    golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 // indirect
  19.  
    golang.org/x/text v0.3.4 // indirect
  20.  
    gopkg.in/ini.v1 v1.62.0 // indirect
  21.  
    gopkg.in/yaml.v2 v2.3.0 // indirect
  22.  
    )
原文地址:https://www.cnblogs.com/ExMan/p/14312174.html