dongqian6234 2018-11-05 12:27
浏览 41
已采纳

动态添加键值映射到结构

I am trying to figure out how I can add the key value pairs of a map[string]string into my prometheus.Labels struct.

If you've got experience with prometheus: I am trying to dynamically add labels and it's values.

labelsMap := make(map[string]string)
labelsMap["nodepool"] = "default"
labelsMap["zone"] = "europe-west"

// here I'd like to add my key / value pairs from my map
containerLabels := prometheus.Labels{
    "node":      "nodename",
    "container": "foo",
    "qos":       "bar",
}
requestedContainerCPUCoresGauge.With(containerLabels).Set(containerMetric.RequestedCPUCores)

My question:

How can I dynamically add the key/value pairs from my given map labelsMap in my containerLabels?

  • 写回答

1条回答 默认 最新

  • doutongwei4380 2018-11-05 12:30
    关注

    You may use a simple for range loop on labelsMap, and add each pair, e.g.:

    containerLabels := prometheus.Labels{}
    for k, v := range labelsMap {
        containerLabels[k] = v
    }
    

    Or since prometheus.Labels is just a simple map:

    type Labels map[string]string
    

    And if you don't want to modify the labelsMap afterwards, a simple type conversion also works:

    containerLabels := prometheus.Labels(labelsMap)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?