0

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!

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.