I have this function:
func GetBasicAuth(w http.ResponseWriter, r *http.Request) (string, error) {
secret, _, ok := r.BasicAuth()
if !ok {
return "", err //is this right?
}
return secret, nil
}
I've had to declare that the function will return a string and an error but in reality it will return one or the other. If the BasicAuth function wasn't ok
then I have no string to return so what do I do here - just send an empty string? This seems weird!
Unless documented otherwise (e.g. io.Reader
), it's normal for Go functions/methods returning a, b, c, …, error
to expect that if err != nil
that all other returned values are undefined and should not be used/examined. It's usual (but not required) that when returning an error the function/method uses whatever the zero value is for those other return values.
As mentioned, some functions/methods such as an io.Reader
's Read(p []byte) (n int, err error)
explicitly state other behaviour:
Callers should always process the n > 0 bytes returned before considering the error err.
And any functions/methods you create that return useful values even in the case of (some) errors should probably explicitly state that.