Home > Software design >  Golang returning a default array of structs
Golang returning a default array of structs

Time:03-30

When I curl an api I get back a response like this:

[{"Hits":25,"Name":"HIT"},{"Hits":87,"Name":"MISS"},{"Hits":15,"Name":"EXPIRED"}]

When a response comes back with 0 values ie, the curl returns this :

[{"Hits":0,"Name":"HIT"},{"Hits":0,"Name":"MISS"},{"Hits":0,"Name":"EXPIRED"}]

What I actually get after unmarshal the json in code with a 0 value response is:

[{1 NONE}]

I actually need the Key names with the 0 values because I'm writing this out to a file eventually to be consumed by another system.

To get around this I created a default array if the return gives me a [{1 NONE}]

For example:

type CHData struct {
    Hits int    `json:"Hits"`
    Name string `json:"Name"`
}

func apiResponse () apiResponseData,err{

    //code that calls the api and returns the response {
    ...
    json.Unmarshal([]byte(body), &apiResponseData)  
    ..
    } 
    

    if len(apiReturneddata) <= 1 { // checks for [{1 NONE}] value
        
        //Default array if api returns with 0 values
        array1 := CHData{Hits: 0, Name: "HIT"}
        array2 := CHData{Hits: 0, Name: "MISS"}
        array3 := CHData{Hits: 0, Name: "EXPIRED"}

        //adding each json into the array of json's
        var mockData []CHData
        mockData = append(mockData, array1)
        mockData = append(mockData, array2)
        mockData = append(mockData, array3)
        log.Println(mockData)

        i, _ := json.Marshal(mockData)
        //log.Println(string(i))

        //Overwrite the "[{1 NONE}]" with [{"Hits":0,"Name":"HIT"},{"Hits":0,"Name":"MISS"},{"Hits":0,"Name":"EXPIRED"}] 
        json.Unmarshal([]byte(i), &apiResponseData)
    }

    return apiResponseData
}
  1. ^ This works BUT is there a better way to do this it seems very verbose, I only have 3 structs in this array but I could have a lot more?
  2. Why does does it return [{1 NONE}] anyway and not the Key:Value struts?

CodePudding user response:

I will assume apiResponseData is []CHData

You should check if the response is none ( 1 entry, 1 hit named None etc)

If yes use a default response.


type apiResponseData []CHData

var defaultAPIResponseData = apiResponseData{
    {0, "HIT"},
    {0, "MISS"},
    {0, "EXPIRED"},
}

func (r apiResponseData) IsNone() bool {
    return len(r) == 1 && r[0].Name == "None"
}
  • Related