Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

retrieveDeviceAuth: Call r.Body.Close() #750

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions deviceauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ func retrieveDeviceAuth(ctx context.Context, c *Config, v url.Values) (*DeviceAu
return nil, err
}

defer r.Body.Close()
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it should be defer r.Body.Close() before reading all the content.

defer r.Body.Close()
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, I'm not sure why we need to use defer, unless io.ReadAll(io.LimitReader(r.Body, 1<<20)) can panic? Anyway, I implemented your suggestion in https://github.com/golang/oauth2/compare/ffeca96aa76167a098068334a567bb7c0975acc8..8499b419ad4097ac16cd5b264b8efe53791ae259. Thanks for reviewing!

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your solution is not wrong, but it's very common in golang to use the defer reader.Close() pattern.
A more precise version that can handle all kind of errors would be:

body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
  r.Body.Close() // ignore _this_ error - we already have one
  ...
  return ...
}
err = r.Body.Close()
if err != nil {
  return ...
}

But this would make the code more unreadable. In most cases it is ok to ignore the close error.

return nil, fmt.Errorf("oauth2: cannot auth device: %v", err)
Expand Down