Skip to content

Instantly share code, notes, and snippets.

@jbowles
Last active December 29, 2015 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbowles/7714593 to your computer and use it in GitHub Desktop.
Save jbowles/7714593 to your computer and use it in GitHub Desktop.
Handler for trying to get megajson to work with HTTP
/*
Trying to use megajson with http.Get(url) but getting Decoding errors.
Have tried with various json responses using various structs.
Decoder errors at various indices (depending on json and structs I'm using):
==========Some Decoding Errors===============
2013/11/29 18:27:23 decoding error: Unexpected comma at 112: ,; expected colon // common for NewMStatusJSONDecoder(resp.Body)
2013/11/29 18:29:14 decoding error: Unexpected null at 153: ; expected '{' or string
2013/11/29 18:39:01 decoding error: Unexpected number at 9: 1.1; expected '{'
2013/11/29 18:40:36 decoding error: Unexpected number at 9: 1.1; expected '{'
2013/11/29 18:41:27 decoding error: Unexpected number at 9: 1.1; expected '{'
==========Some Decoding Errors===============
*/
func WunderObj(w http.ResponseWriter, req *http.Request) {
// returns *Response, error
// *Response.body returns io.ReadCloser
// io.ReadCloser implements ReadCloser interface
resp, err := http.Get(url)
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
// originally had problems with decoding the resp.Body.
// So I figured I'd try to create a NewReader that implements Reader interface
// So that NewMStatusDecoder(), which accepts io.Reader, might have a better chance.
// Nothing worked.
// DumpResponse takes *Response and arg for body=(true|false) and returns []byte, error
d, _ := httputil.DumpResponse(resp, true)
// NewReader takes []byte, returns Reader
b := bytes.NewReader(d)
var obs *MStatus
//NOTE: see https://gist.github.com/jbowles/7714619
// By cleaning up the API and regenerating decoder I got this to work
// by simply NewMStatusJSONDecoder(resp.Body)
// BUT, the API and the Decoder have to match exaclty AND there can be no 'null' values.
nojd := NewMStatusJSONDecoder(b)
// also tried NewMStatusJSONDecoder(resp.Body) and got similar errors
if err := nojd.Decode(&obs); err != nil {
log.Fatalln("decoding error: ", err.Error())
}
fmt.Fprintf(w, "%s", &nojd)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment