Peter Hon Peter Hon - 3 months ago 86
JSON Question

golang invalid character 'b' looking for beginning of value

I am trying to post a json with xml message inside it. However it returns

invalid character 'b' looking for beginning of value

I think the possible reason is that I am trying to marshal the returns body which is not in json format.

func (s *BackendConfiguration) Do(req *http.Request, v interface{}) error {
log.Printf("Requesting %v %v%v\n", req.Method, req.URL.Host, req.URL.Path)
start := time.Now()

res, err := s.HTTPClient.Do(req)

if debug {
log.Printf("Completed in %v\n", time.Since(start))
}

if err != nil {
log.Printf("Request to sakura failed: %v\n", err)
return err
}
defer res.Body.Close()

resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Cannot parse sakura response: %v\n", err)
return err
}

if debug {
log.Printf("sakura response: %q\n", resBody)
}

if v != nil {
return json.Unmarshal(resBody, v)
}

return nil
}


The error happened at this line

return json.Unmarshal(resBody, v)

Answer

The error indicates that the server did not return a valid JSON response. I suggest adding the following code to debug the issue:

err := json.Unmarshal(resBody, v)
if err != nil {
    log.Printf("error decoding sakura response: %v", err)
    if e, ok := err.(*json.SyntaxError); ok {
        log.Printf("syntax error at byte offset %d", e.Offset)
    }
    log.Printf("sakura response: %q", resBody)
    return err
}
Comments