内容简介:本篇将介绍如何处理应用程序的可选配置,并在具有文件配置的实际案例中使用功能选项模式。
本篇将介绍如何处理应用程序的可选配置,并在具有文件配置的实际案例中使用功能选项模式。
带功能选项的文件配置
Golang 版本
1.12.1
前言
本篇将介绍如何处理应用程序的可选配置,并在具有文件配置的实际案例中使用功能选项模式。
实现
创建文件 main.go
,代码如下:
package main
import (
"encoding/json"
"fmt"
"os"
)
type Client struct {
consulIP string
connString string
}
func (c *Client) String() string {
return fmt.Sprintf("ConsulIP:%s,connString:%s", c.consulIP, c.connString)
}
var defaultClient = Client{
consulIP: "localhost:9000",
connString: "postgres://localhost:5432",
}
// ConfigFunc用作要在功能选项中使用的类型
type ConfigFunc func(opt *Client)
// FromFile func返回ConfigFunc类型。这样它就可以从json读取配置
func FromFile(path string) ConfigFunc {
return func(opt *Client) {
f, err := os.Open(path)
if err != nil {
panic(err)
}
defer f.Close()
decoder := json.NewDecoder(f)
fop := struct {
ConsulIP string `json:"consul_ip"`
}{}
err = decoder.Decode(&fop)
if err != nil {
panic(err)
}
opt.consulIP = fop.ConsulIP
}
}
// FromEnv从环境变量读取配置并将它们与现有变量组合
func FromEnv() ConfigFunc {
return func(opt *Client) {
connStr, exist := os.LookupEnv("CONN_DB")
if exist {
opt.connString = connStr
}
}
}
func NewClient(opts ...ConfigFunc) *Client {
client := defaultClient
for _, val := range opts {
val(&client)
}
return &client
}
func main() {
client := NewClient(FromFile("config.json"), FromEnv())
fmt.Println(client.String())
}
创建文件 config.json
,内容如下:
{
"consul_ip":"127.0.0.1"
}
$ export CONN_DB=oracle://local:5921 && go run main.go ConsulIP:127.0.0.1,connString:oracle://local:5921
原理
函数选项模式的核心概念是配置API包含函数参数。在本例中, NewClient
函数接受不同数量的 ConfigFunc
参数,然后在 defaultClient
结构上逐一应用这些参数。通过这种方式,可以非常灵活地修改默认配置。
请参阅 FromFile
和 FromEnv
函数,它们返回 ConfigFunc
,实际上是访问文件或环境变量。
最后,可以检查输出,其中包含来自文件和环境变量的值。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 橙单中台化低代码生成器 v1.3 发布,支持 Mybatis Plus 及更多代码生成配置选项。
- 横向的选项卡效果
- go中函数选项模式
- .NET Core微服务开发选项
- UNP 学习笔记——套接字选项
- 实用的可选项(Optional)扩展
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
High Performance Python
Micha Gorelick、Ian Ozsvald / O'Reilly Media / 2014-9-10 / USD 39.99
If you're an experienced Python programmer, High Performance Python will guide you through the various routes of code optimization. You'll learn how to use smarter algorithms and leverage peripheral t......一起来看看 《High Performance Python》 这本书的介绍吧!