动态添加键值映射到结构

Dynamically add key value map to struct

我想知道如何将 map[string]string 的键值对添加到我的 prometheus.Labels 结构中。

如果您有使用 prometheus 的经验:我正在尝试动态添加标签及其值。

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)

我的问题:

如何在我的 containerLabels 中动态添加给定地图 labelsMap 中的 key/value 对?

您可以在 labelsMap 上使用简单的 for range 循环,然后添加每一对,例如:

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

或者因为 prometheus.Labels 只是一个简单的地图:

type Labels map[string]string

如果你不想在之后修改 labelsMap,一个简单的类型 conversion 也可以:

containerLabels := prometheus.Labels(labelsMap)