I am working with a 3rd party API endpoint that can return one of two top-level JSON objects for the same HTTP status code. I have not been happy with the solutions I have found so far so I came up with the following solution using embedded types:
type TokenError struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
type Token struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
}
type TokenResponse struct {
*TokenError
*Token
}
With the above types, I can do a single unmarshal and some simple checks:
var tokenResponse TokenResponse
err = json.Unmarshal(body, &tokenResponse)
if err != nil {
fmt.Printf("Error parsing response %+v
", err)
}
if tokenResponse.TokenError != nil {
fmt.Printf("Error fetching token: %+v
", tokenResponse.TokenError)
return
}
if tokenResponse.Token != nil {
fmt.Printf("Successfully got token: %+v
", tokenResponse.Token)
return
}
I am wondering the following:
TokenResponse
type outside of the package...)