• [go每日一库] golang viper实现动态配置更新 Marathon


    viper库下载:

    go get -u github.com/spf13/viper
    

    代码结构:

    .
    +--- config
    |   +--- config.go
    |   +--- config.yaml
    +--- go.mod
    +--- go.sum
    +--- main.go
    

    config.yaml

    app:
      app1:
        timeout: 120
        rpc: true
        compatible: true
    
    mysql:
      host: localhost
      port: 3306
      user: root
      password: root
      database: test
      
    redis:
      host: localhost
      port: 6379
      dbname: 0
    

    config.go

    package config
    
    import (
    	"fmt"
    	"github.com/fsnotify/fsnotify"
    	"github.com/spf13/viper"
    )
    
    type Config struct {
    	App   App
    	MySQL MySQL
    	Redis Redis
    }
    
    type App struct {
    	App1 App1
    }
    
    type App1 struct {
    	Timeout    int
    	Rpc        bool
    	Compatible bool
    }
    
    type MySQL struct {
    	Host     string
    	User     string
    	Password string
    	Port     int
    	Database string
    }
    
    type Redis struct {
    	Host   string
    	Port   int
    	Dbname int
    }
    
    var AppConfig Config
    
    func init()  {
    	viperCfg := viper.New()
    
    	viperCfg.SetConfigName("config")
    	viperCfg.SetConfigType("yaml")
    	viperCfg.AddConfigPath("D:\\demo1\\src\\demo\\demo06\\go-viper-http-watch\\config\\")
    
    	viperCfg.ReadInConfig()
    
    	err := viperCfg.Unmarshal(&AppConfig)
    	if err != nil {
    		fmt.Println(err)
    	}
    
    	viperCfg.WatchConfig()
    	viperCfg.OnConfigChange(func(e fsnotify.Event) {
    		fmt.Println("Config file changed:", e.Name)
    		if err = viperCfg.Unmarshal(&AppConfig); err != nil {
    			fmt.Println(err)
    		}
    	})
    }
    
    func GetConfig() Config {
    	return AppConfig
    }
    

    main

    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	. "go-viper-http-watch/config"
    	"net/http"
    )
    
    func main()  {
    	router := gin.Default()
    
    	router.GET("/info", func(ctx *gin.Context) {
    		ctx.JSON(http.StatusOK, gin.H{
    			"code": 0,
    			"msg": AppConfig.MySQL.Host,
    		})
    	})
    
    	router.Run(":8080")
    }
    

    go.mod

    module go-viper-http-watch
    
    go 1.16
    
    require (
    	github.com/fsnotify/fsnotify v1.5.4
    	github.com/gin-gonic/gin v1.8.1
    	github.com/spf13/viper v1.12.0
    )
    
    replace go-viper-http-watch => ../go-viper-http-watch
    
  • 相关阅读:
    【ALearning】第三章 Android基本常见控件
    【问题汇总】ListView的FooterView设置可见性的问题
    shell重定向调试信息
    Android提供的系统服务之--TelephonyManager(电话管理器)
    工作一年的总结
    【甘道夫】HBase基本数据操作的详细说明【完整版,精绝】
    未定义标识符_ConnectionPtr
    POJ 1329 三角外接圆
    IOS开发-加载本地音乐
    SQL Server 性能优化3 该指数(Index)保养
  • 原文地址:https://www.cnblogs.com/davis12/p/16363131.html
Copyright © 2020-2023  润新知