golang整洁之道(一)

设计工整的go项目配置文件

问题背景

  • 项目常常会涉及到配置文件,而配置文件每每包含多方的配置信息,可能同时涉及到MySQL,kafka,hive,hdfs等等。

不加思索的yaml配置文件

  • 最快,最直接的方案天然是以下示例,直接写
  1. yaml部分golang

    hdfs_path: "/user/hive/warehouse/dm_user.db/user_vod_time/create_time="
    hdfs_host: "hdfsNode9"
    hdfs_port: "8020"
    eth_host: "http://127.0.0.1"
    eth_port: "8545"
    coin_password: "password"
  2. golang部分数据结构

    package config
    
    type config struct{
        HDFSPath string `yaml:"hdfs_path"`
        HDFSHost string `yaml:"hdfs_host"`
        HDFSPort string `yaml:"hdfs_port"`
        EthHost string `yaml:"eth_host"`
        EthPort string `yaml:"eth_port"`
        EthCoinPassword string `yaml:"coin_password"`
    }

这个方案存在什么问题

  1. 没有条理,虽然在命名方面能够看出来对应的各个部分的配置,可是不够清晰。假如项目规模增大,配置文件内容看上去就是一大坨
  2. 每个包,可能须要再额外定义一个相似的结构,保存相应的配置,形成代码的冗余。毕竟,以上边这个例子来讲,HDFS的处理跟ETH的处理不可能放在一个package里,那对应的包要不要再定义一个数据结构,保存配置数据呢?

更加清晰的yaml配置文件

  • 利用golang struct的组合特性,就能够让结构更加清晰,减小代码冗余
  1. yaml文件设计

    hdfs: {
        path: "/user/hive/warehouse/dm_user.db/user_vod_time/create_time=",
        host: "hdfsNode9",
        port: "8020"
    }
    eth: {
        host: "http://127.0.0.1",
        port: "8545",
        coin_password: "password",
    }
  2. golang 文件——config包code

    type config struct {
        hdfs.HDFSConfig `yaml:"hdfs"`
        eth.EthConfig `yaml:"eth"`
    }
  3. golang文件——eth包接口

    type EthConfig struct {
        EthHost string `yaml:"host"`
        EthPort string `yaml:"port"`
        EthCoinPassword string `yaml:"coin_password"`
    }
  4. golang文件——hdfs包kafka

    type HDFSConfig struct {
        HDFSPath string `yaml:"path"`
        HDFSHost string `yaml:"host"`
        HDFSPort string `yaml:"port"`
    }

总结

  • 整个配置文件和代码结构,重构以后瞬间清晰了不少。用代码实现需求一般不难,大部分时候都有别人写好的接口,直接调用就能够。可是要想写好golang,让结构清晰,代码健壮,接下来还须要花不少功夫。(借助struct的组合,经常能够让代码结构更加清晰)
相关文章
相关标签/搜索