Skip to content

Instantly share code, notes, and snippets.

@sathishvj
Last active December 29, 2016 08:24
Show Gist options
  • Save sathishvj/aeda6a245ad0e1c26095597370220a20 to your computer and use it in GitHub Desktop.
Save sathishvj/aeda6a245ad0e1c26095597370220a20 to your computer and use it in GitHub Desktop.
Custom json decoding to check for error or other data
// play link: https://play.golang.org/p/xf43Ta309p
// golan-nuts ref: https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/gg4T4jMuz0U
package main
import (
"encoding/json"
"errors"
"fmt"
)
type ErrResponse struct {
Error string `json:"error"`
}
func isErrResponse(resp string) error {
var any interface{}
err := json.Unmarshal([]byte(resp), &any)
if err != nil {
return err
}
switch v := any.(type) {
case map[string]interface{}:
if msg, ok := v["error"]; ok {
s, isString := msg.(string) // only if the value is of string type
if isString && s != "" {
return errors.New(s)
}
return nil
}
fmt.Printf("JSON data is an object: %v\n", v)
return nil
/*
case []interface{}:
fmt.Printf("JSON data is an array: %v\n", v)
return nil
default:
fmt.Printf("JSON data is of type %T: %#v:\n", v, v)
return nil
*/
}
return nil
}
func main() {
err := isErrResponse(`
{
"error": "there was an error"
}
`)
fmt.Printf("1. %+v\n", err)
err = isErrResponse(`
[
{"name": "carrie"}
]
`)
fmt.Printf("2. %+v\n", err)
err = isErrResponse(`
{
"error": 5
}
`)
fmt.Printf("3. %+v\n", err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment