JSON Schema in struct object list

Started with go today… overall I like it but there are a few things I am still trying to understand like how to create a struct with a tuple… I have the following json schema I want to reply with.

[
 {
  "cmd": "string",
  "service": "string",
  "src": "string",
  "dest": "string",
  "weight": float,
  "tags": ["string"],
  "opts": {"string":"string"}
 }
]

and I have the following code

type consulService struct {
    Cmd     string   `json:"cmd"`
    Service string   `json:"service"`
    Src     string   `json:"src"`
    Dest    string   `json:"dest"`
    Weight  float32  `json:"weight"`
    Tags    []string `json:"tags"`
    Opts    []string `json:"opts"`
}

func getConsulServices(w http.ResponseWriter, req *http.Request) {

    consultServiceCatalg := []consulService{
        {
            Cmd:     "test",
            Service: "CustomService",
            Src:     "/",
            Dest:    "http://1.1.1.1:5555/",
            Weight:  100,
            Tags:    []string{"custom","service"},
            Opts:    {"k1" :"s1", "k2": "s2", "Kn":"etc"},
        },
    }

    fmt.Println(consultServiceCatalg)

    js, err := json.Marshal(consultServiceCatalg)

    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")

    w.Write(js)
}

My problem is the Opts variable… how can i represent a list of strings in the type object… do I need to create a new type Opts…with Key Value of type string… in short a tuple, but I was not able to find that type in golang…

The big problem here is that the Key is dynamic and not static.

This is probably obvious for someone with more than a day of experience in go. Thks

map[string]string

1 Like

Thanks for pointing me in the right direction @mje

I learned about maps

type consulService struct {
    Cmd     string            `json:"cmd"`
    Service string            `json:"service"`
    Src     string            `json:"src"`
    Dst     string            `json:"dst"`
    Weight  float32           `json:"weight"`
    Tags    []string          `json:"tags"`
    Opts    map[string]string `json:"opts"`
}

func getConsulServices(w http.ResponseWriter, req *http.Request) {

    consultServiceCatalg := []consulService{
        {
            Cmd:     "route add",
            Service: "CustomService",
            Src:     "/home",
            Dst:     "http://1.1.1.1",
            Weight:  100,
            Tags:    []string{"custom"},
            Opts:    map[string]string{"strip": "/path", "proto": "tcp"},
        },
    }

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.