jaxxstorm
jaxxstorm

Reputation: 13241

map[string]string inside a struct

Apologies for the title, but this is a weird one and out of my ability to understand.

I'm working with a go library that's sort of finished, but sort of not:

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

The statuspage.io API supports the following params when posting an incident:

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

An example would be:

"incident[components][ftgks51sfs2d]=degraded_performance"

Unfortunately, the struct defined in the library 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,
    })
}

How can I update this struct (and the associated encodeParams function) to support passing an arbitrary map of components and associated statuses?

Upvotes: 1

Views: 1177

Answers (1)

Adam Smith
Adam Smith

Reputation: 54162

You could embed a NewIncidentUpdate inside your own struct that defines the component status changes.

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

then define String the same way, while accomodating for your ComponentStatusChanges map.

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)
}

Upvotes: 1

Related Questions