go - 结构中的 map[string]string

标签 go

为标题道歉,但这是一个奇怪的标题,超出了我的理解能力。

我正在使用一个已经完成但还没有完成的 go 库:

https://github.com/yfronto/go-statuspage-api

statuspage.io API 在发布事件时支持以下参数:

incident[components][component_id] - Map of status changes to apply to affected components.

一个例子是:

"incident[components][ftgks51sfs2d]=degraded_performance"

不幸的是,库中定义的结构doesn't support that particular field :

type NewIncidentUpdate struct {
    Name               string
    Status             string
    Message            string
    WantsTwitterUpdate bool
    ImpactOverride     string
    ComponentIDs       []string
}

func (i *NewIncidentUpdate) String() string {
    return encodeParams(map[string]interface{}{
        "incident[name]":                 i.Name,
        "incident[status]":               i.Status,
        "incident[message]":              i.Message,
        "incident[wants_twitter_update]": i.WantsTwitterUpdate,
        "incident[impact_override]":      i.ImpactOverride,
        "incident[component_ids]":        i.ComponentIDs,
    })
}

我如何更新此结构(和 the associated encodeParams function)以支持传递组件和关联状态的任意映射?

最佳答案

您可以在您自己的结构中嵌入一个 NewIncidentUpdate 来定义组件状态更改。

type MyIncidentUpdate struct {
    NewIncidentUpdate
    ComponentStatusChanges map[string]string
}

然后以相同的方式定义 String,同时适应您的 ComponentStatusChanges 映射。

func (i *MyIncidentUpdate) String() string {
    params := map[string]interface{}{
        "incident[name]":                 i.Name,
        "incident[status]":               i.Status,
        "incident[message]":              i.Message,
        "incident[wants_twitter_update]": i.WantsTwitterUpdate,
        "incident[impact_override]":      i.ImpactOverride,
        "incident[component_ids]":        i.ComponentIDs,
    }
    for k, val := range i.ComponentStatusChanges {
        key := fmt.Sprintf("incident[components][%s]", k)
        params[key] = val
    }

    return encodeParams(params)
}

关于go - 结构中的 map[string]string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51622733/

相关文章:

go - 如何从 Go 中的字符串列表初始化类型、字符串 slice

string - 如何保存呈现的模板而不是打印到 os.Stdout?

go - 为什么我的普罗米修斯标签不显示?

go - Golang 中的不可变结构

戈朗/戈尔姆 : api end point returning only last record

go - Go 编译错误 : cannot use new(SimpleChaincode)

go - 从 slice 中删除元素差异 gccgo 与 gc

git - 在自定义 GO 包之上提交

xml - Golang 解析带有同名嵌套节点的 XML?

go - 在 golang 反射 FieldByName 中忽略大小写