I have the following struct
type GiphyJson struct {
Type string `json:"type"`
Data []struct {
Images struct {
Fixed_height struct {
Url string `json:"url"`
} `json:"fixed_height"`
} `json:"images"`
} `json:"data"`
}
and I need to access Data[x].Images.Fixed_height.Url
. Ideally I'd like to be able to check for the existence of each of the Properties 'Data, Images, ,Fixed_height' before accessing Url to ensure I don't have a nil pointer exceptions. Since I'm fairly new to the language I was curious what the idiomatic way of doing this would be.
The following is how i'm using the struct.
var err error
var giphyJson GiphyJson
keyword = url.QueryEscape(keyword)
resp, err := http.Get("http://api.giphy.com/v1/gifs/search?q=" + keyword + "&api_key=dc6zaTOxFJmzC&limit=100")
if err != nil {
err = errors.New("An error occured trying to contact giphy")
return "", err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(bodyBytes, &giphyJson)
The only required check (based on the definition of that struct) is that len(Data) > x
. Beyond that, everything is a value type so there is no risk of a nil reference panic happening.
if len(Data) > x {
// access
fmt.Println(Data[x].Images.Fixed_height.Url)
} else {
// do other stuff you to mitigate unexpected input
}