doumu6941 2017-09-21 18:49
浏览 13

仅从struct返回特定字段

I have a pair of structs like so:

  type Datacenter struct {
    Name  string
    Key   string
    Hosts []Host
  }

  type Host struct {
    Name string
    Port int
  }

And then an example configuration file:

datacenters:
  - name: dc1
    key: test
    hosts:
      - name: dc1-host
        port: 8200
  - name: dc2
    key: dc-test
    hosts:
      - name: dc2-host
        port: 8200

I'm using viper to read the configuration file, here's the function:

func getDatacenters() []config.Datacenter {

  err := viper.UnmarshalKey("datacenters", &datacenters)

  if err != nil {
    log.Error("Unable to read hosts key in config file: %s", err)
  }

  return datacenters

}

What I'd like to be able do now is specify an optional parameter, datacenter and if that's specified, to only return the keys from that datacenter. If the parameter is not specified, I'd like it to unmarshal and return the whole thing.

Is this possible?

EDIT: I should add, all I do with this so far is range over them:

for _, d := range datacenters {
      for _, h := range d.Hosts {
  }
}

So it may be there's a better way.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 opencv图像处理,需要四个处理结果图
    • ¥15 无线移动边缘计算系统中的系统模型
    • ¥15 深度学习中的画图问题
    • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
    • ¥15 Python报错怎么解决
    • ¥15 simulink如何调用DLL文件
    • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
    • ¥30 线性代数的问题,我真的忘了线代的知识了
    • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
    • ¥188 需要修改一个工具,懂得汇编的人来。