req, err := http.NewRequest(method, url, bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
if req == nil {
//handle of nil
}
According to the Go Code Review Comments:
“Don’t treat ‘not found’ as an application error. Handle it at a higher level when it makes sense.”
In this case, we might assume that if err == nil, then req is valid. But what if, someday, the implementation changes and req is nil without an error? That could cause a panic in the application. How do you handle this scenario?
In this case you need to check if reg is nil as your are doing in your code. But thinking in this problem return nil when you expected to return “something” can be flag as an error. I could check that situation in the function code and if it is happened i would return an error just to be consistent
You can handle it on the basis of the back compatibility promise. Everything what is implemented this way in the standard library will stay like it. You cannot protect your code from everything what might or might not happen.
In this case, I think it’s safe to assume that req will always be non-nil if err is nil. But I wish they included that as a comment in the documentation rather than having it be implied.