Created
April 17, 2012 17:58
-
-
Save kylelemons/2407845 to your computer and use it in GitHub Desktop.
Decoding JSON within a wrapper using interface{}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io" | |
"strings" | |
) | |
type ResponseError struct { | |
Code int | |
Message string | |
} | |
func (e ResponseError) Error() string { | |
return fmt.Sprintf("[%d] %s", e.Code, e.Message) | |
} | |
type Response struct { | |
Result interface{} | |
Error *ResponseError | |
} | |
// Decode decodes the response from r writing the result into the struct | |
// pointed to by want. | |
func Decode(r io.Reader, want interface{}) error { | |
resp := &Response{Result: want} | |
if err := json.NewDecoder(r).Decode(resp); err != nil { | |
return err | |
} | |
if resp.Error != nil { | |
return resp.Error | |
} | |
return nil | |
} | |
func main() { | |
type a struct { | |
Str string | |
} | |
type b struct { | |
X, Y int | |
} | |
for js, resp := range map[string]interface{}{ | |
`{"Result":{"Str":"42"}}`: &a{}, | |
`{"Result":{"X":6,"Y":9}}`: &b{}, | |
`{"Error":{"Code":400,"Message":"Unauthorized"}}`: &a{}, | |
} { | |
if err := Decode(strings.NewReader(js), resp); err != nil { | |
fmt.Printf("%q: error %q\n", js, err) | |
continue | |
} | |
fmt.Printf("%q: %#v\n", js, resp) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment