jnichols-git/Gate

Error handling with Go Readers/Writers

Opened this issue · 1 comments

Readers and Writers in Golang have interesting error behavior. Generally, any read/write operations will return an int count of how many pieces of data (usually bytes) were read into a slice. If that count is less than expected, an error will also be returned. These errors don't mean a permanent failure to read, so they can't just fail out of a function.

I was unable to find resources on handling these errors, and would love some help if someone is more knowledgeable about those particular operations.

I believe this postcondition is rarely used, as this doesn't make sense to implement for most Readers. Take this excerpt for example:

bodyReader := req.Body
body, err := ioutil.ReadAll(bodyReader)
if err != nil {
    return err
}
if err := json.Unmarshal(body, out); err != nil {
    return err
}
return nil

req.Body implements io.ReadCloser, so it must implement both Read() and Close(). Completely draining a raw request body (body, err := ioutil.ReadAll(bodyReader)) probably won't return an error except for EOF, since it treats the body as a simple stream of bytes.