教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Go Web实战-2.配置文件

Go Web实战-2.配置文件

发布时间:2021-12-17   编辑:jiaochengji.com
教程集为您提供Go Web实战-2.配置文件等资源,欢迎您收藏本站,我们将为您提供最新的Go Web实战-2.配置文件资源

        为了更好的集中管理项目的配置文件,引入了viper。git地址 https://github.com/spf13/viper

什么是viper,官方解释:

Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application, and can handle all types of configuration needs and formats. It supports:

<ul style="padding-left:2em;margin-bottom:16px;color:rgb(36,41,46);font-family:'-apple-system', BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';"><li>setting defaults</li><li style="margin-top:.25em;">reading from JSON, TOML, YAML, HCL, and Java properties config files</li><li style="margin-top:.25em;">live watching and re-reading of config files (optional)</li><li style="margin-top:.25em;">reading from environment variables</li><li style="margin-top:.25em;">reading from remote config systems (etcd or Consul), and watching changes</li><li style="margin-top:.25em;">reading from command line flags</li><li style="margin-top:.25em;">reading from buffer</li><li style="margin-top:.25em;">setting explicit values</li></ul>

Viper can be thought of as a registry for all of your applications configuration needs.

         主要api:

<ul style="padding-left:2em;margin-bottom:16px;color:rgb(36,41,46);font-family:'-apple-system', BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';"><li><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">Get(key string) : interface{}</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">GetBool(key string) : bool</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">GetFloat64(key string) : float64</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">GetInt(key string) : int</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">GetString(key string) : string</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">GetStringMap(key string) : map[string]interface{}</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">GetStringMapString(key string) : map[string]string</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">GetStringSlice(key string) : []string</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">GetTime(key string) : time.Time</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">GetDuration(key string) : time.Duration</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">IsSet(key string) : bool</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">
</code></li></ul>

        viper是国外大牛写的一个牛逼的配置管理库,支持的语言的也比较多,<span style="color:rgb(36,41,46);font-family:'-apple-system', BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';text-align:left;">JSON, TOML, YAML, HCL, Java properties都可以,而且还能远程读取配置,这个做微服务配置中心挺合适。</span>

<span style="color:rgb(36,41,46);font-family:'-apple-system', BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';text-align:left;"><span style="color:rgb(36,41,46);font-family:'-apple-system', BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';text-align:left;">          这里我还是用yaml来写配置参数。</span>
</span>

<h4><span style="color:rgb(36,41,46);font-family:'-apple-system', BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';text-align:left;">安装</span></h4> <pre><code class="language-html">go get github.com/spf13/viper</code></pre> <h4>主要步骤</h4>

<ol><li>写好配置文件</li><li>设置viper查找的文件目录</li><li>设置配置文件名称</li><li>读取参数</li></ol><h4>实现步骤</h4>

首先我们创建目录放配置文件和程序。


yaml文件夹里面是配置文件,param里面是参数模块。

我添加了两个参数模块,分别是应用参数和数据源参数,我们看一下application.yaml里面的参数:

<pre><code class="language-java">application: mode: debug #gin的启动模式, debug or release or test server: port: 8080 datasource: #多数据源使用数据源名称做主键保存到参数列表 user: #key dialect: mysql url: jdbc:mysql://localhost:3306/base_user?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true username: root password: root maxIdle: 200 maxOpen: 50 admin: #key dialect: mysql url: jdbc:mysql://localhost:3306/base_admin?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true username: root password: root maxIdle: 200 maxOpen: 50</code></pre>

InitConfig.go是参数配置的入口,其init在main导入config包后调用,InitConfig.go内容如下

<pre><code class="language-java">type ConfigParam struct { App AppParam //应用参数 Dbs DbParam //数据源参数 } var Config ConfigParam func init(){ fmt.Println("[init config params]......") viper.SetConfigType("yaml") viper.SetConfigName("application") // name of config file (without extension) viper.AddConfigPath("./config/yaml") // 配置文件路径,多次使用可以查找多个目录 err := viper.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file panic(fmt.Errorf("Fatal error config file: %s \n", err)) return } //加载配置 Config.App.ReadConfig() Config.Dbs.ReadConfig() fmt.Println("[end init config params]......") }</code></pre>

里面创建了个全局参数Config供应用调用。Config里面是两个模块的参数。

init里面首先设置了配置文件名称和路径,然后调用参数模块的ReadConfig方法加载参数。

先看AppParam的加载

<pre><code class="language-java">type server struct { Mode string Port string } type AppParam struct { server } func (p *AppParam)ReadConfig(){ //default config viper.SetDefault("application.mode", "debug") viper.SetDefault("application.server.port","8080") //read properties p.Mode = viper.GetString("application.mode") //注意server的port数字前面有个冒号 p.Port = ":" viper.GetString("application.server.port") fmt.Println("[Init AppParam Over]...", p) }</code></pre>

这个比较简单,直接通过viper的方法读取配置文件里面的字符串。这里我们先给两个参数设置了默认值,当配置文件里面没有找到参数时viper会自动加载默认值。

然后是DbParam的加载

<pre><code class="language-java">type datasource struct { Dialect string Url string Username string Password string MaxIdle int MaxOpen int } //多数据源支持,map[name]= db type DbParam struct { //数据源数量 Cnt int //数据源map Source map[string]datasource } func (p *DbParam) ReadConfig() { //default config //viper.SetDefault("ContentDir", "content") //viper.SetDefault("ContentDir", "content") p.Source = make(map[string]datasource) err := viper.UnmarshalKey("datasource", &p.Source) if err != nil { panic(err) return } p.Cnt = len(p.Source) fmt.Println("[Init DbParam Over]...", p) } </code></pre>

viper内置了类似反序列化的工具,实际使用的是mapstructure这个库,主要功能就是把map转struct。

<ul style="padding-left:2em;margin-bottom:16px;color:rgb(36,41,46);font-family:'-apple-system', BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';"><li><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">Unmarshal(rawVal interface{}) : error</code></li><li style="margin-top:.25em;"><code style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;padding:.2em .4em;margin:0px;background-color:rgba(27,31,35,.0470588);">UnmarshalKey(key string, rawVal interface{}) : error</code></li></ul><pre style="font-family:'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;font-size:13.6px;margin-bottom:0px;padding-top:16px;padding-bottom:16px;line-height:1.45;background-color:rgb(246,248,250);color:rgb(36,41,46);"><span class="pl-k" style="color:rgb(215,58,73);">type</span> config <span class="pl-k" style="color:rgb(215,58,73);">struct</span> { <span class="pl-v" style="color:rgb(227,98,9);">Port</span> <span class="pl-k" style="color:rgb(215,58,73);">int</span> <span class="pl-v" style="color:rgb(227,98,9);">Name</span> <span class="pl-k" style="color:rgb(215,58,73);">string</span> <span class="pl-v" style="color:rgb(227,98,9);">PathMap</span> <span class="pl-k" style="color:rgb(215,58,73);">string</span> <span class="pl-s" style="color:rgb(3,47,98);"><span class="pl-pds">`</span>mapstructure:"path_map"<span class="pl-pds">`</span></span> } <span class="pl-k" style="color:rgb(215,58,73);">var</span> <span class="pl-smi">C</span> config <span class="pl-smi">err</span> <span class="pl-k" style="color:rgb(215,58,73);">:=</span> <span class="pl-c1" style="color:rgb(0,92,197);">Unmarshal</span>(&C) <span class="pl-k" style="color:rgb(215,58,73);">if</span> err != <span class="pl-c1" style="color:rgb(0,92,197);">nil</span> { t.<span class="pl-c1" style="color:rgb(0,92,197);">Fatalf</span>(<span class="pl-s" style="color:rgb(3,47,98);"><span class="pl-pds">"</span>unable to decode into struct, <span class="pl-c1" style="color:rgb(0,92,197);">%v</span><span class="pl-pds">"</span></span>, err) }</pre>


这里把map转struct后保存到DbParam.source里面,使用“name”做数据源的主键, 然后就可以在其他地方使用参数了。

main函数里面使用参数

<pre><code class="language-java">func main() { fmt.Println("[Server Starting]...") gin.SetMode(Config.App.Mode) //注册路由 router := routers.InitRouter() //启动服务器 router.Run(Config.App.Port) log.Println("Server stopped") //defer models.DbClose() os.Exit(0) }</code></pre>

启动程序,查看打印的参数

<pre><code class="language-java">[Init AppParam Over]... &{{debug :8080}} [Init DbParam Over]... &{2 map[user:{mysql jdbc:mysql://localhost:3306/base_user?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true root root 200 50} admin:{mysql jdbc:mysql://localhost:3306/base_admin?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true root root 200 50}]} [end init config params]...... </code></pre>
到此这篇关于“Go Web实战-2.配置文件”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
2018年最全Go语言教程零基础入门到进阶实战视频
VSCode配置golang开发环境
想系统学习GO语言(Golang
Go语言 零基础入门到精通项目实战
golang ide 环境搭建_Go语言环境搭建详解(2020版)
Go语言从入门到精通 -【web项目实战篇】- 读取配置文件
go run main.go 参数_Go语言入门:Hello world
go语言实战教程:项目文件配置和项目初始化运行
[GO语言基础] 一.为什么我要学习Golang以及GO语言入门普及
Go语言爱好者周刊:第 78 期 — 这道关于 goroutine 的题

[关闭]
~ ~