A little over a year ago, Go added an Offset
value to the json.UnmarshalTypeError
type (see closed issue here for context). The purpose behind the offset value makes sense, but I'm not sure how it can be used when reading a go http response body, which is of type io.ReadCloser
.
// An UnmarshalTypeError describes a JSON value that was
// not appropriate for a value of a specific Go type.
type UnmarshalTypeError struct {
Value string // description of JSON value - "bool", "array", "number -5"
Type reflect.Type // type of Go value it could not be assigned to
Offset int64 // error occurred after reading Offset bytes
}
For example:
var body CustomType
decoderErr := json.NewDecoder(response.Body).Decode(&body)
if decoderErr != nil {
if typeError, ok := decoderErr.(*json.UnmarshalTypeError); ok {
// Do something with typeError.Offset here
}
}
At the point of the error getting caught, I've already read from response.Body
via json.NewDecoder...
. I'm looking for a way to read response.Body
again, but only up to the point of the error by using the Offset value in typeError.