zoukankan      html  css  js  c++  java
  • 1.12 配置文件读取

    config.json

    {
        "consul_ip":"127.0.0.1"
    }
    
    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"os"
    )
    
    type Client struct {
    	consulIP   string
    	connString string
    }
    
    func (c *Client) String() string {
    	return fmt.Sprintf("ConsulIP: %s , Connection String: %s",
    		c.consulIP, c.connString)
    }
    
    var defaultClient = Client{
    	consulIP:   "localhost:9000",
    	connString: "postgres://localhost:5432",
    }
    
    // ConfigFunc works as a type to be used
    // in functional options
    type ConfigFunc func(opt *Client)
    
    // FromFile func returns the ConfigFunc
    // type. So this way it could read the configuration
    // from the 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 reads the configuration
    // from the environmental variables
    // and combines them with existing ones.
    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())
    }
    
    
    /*
    ConsulIP: 127.0.0.1 , Connection String: postgres://localhost:5432
    */
    
    
  • 相关阅读:
    idea设置docker远程插件
    Linux安装nfs共享文件
    类文件注释规约
    标准pcm数据(正弦波、方波、三角波)解读
    dB分贝计算
    Ion内存的带cahce与不带cache问题分享
    c++智能指针介绍_补充
    c++智能指针介绍
    wav封装格式
    开博啦。。。
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8593496.html
Copyright © 2011-2022 走看看