Reputation: 1706
I'm a little confused about http handlers and handling something like errors or redirects.
For example, if I have to redirect because of some conditional check, should I be doing the following:
func SomeHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
if thisThing != thatThing {
log.Print("thisThing not equal to thatThing - redirecting")
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return // <-- is this necessary?
}
}
Upvotes: 2
Views: 717
Reputation: 12875
return
is used for preliminary exit from the function and returning value to caller. As it was pointed before if there’s no more instruction function will exit but itself
When to use return
?
One of key ideas of Go is readability - every program should be easy to read. So Go code is structured vertically - main flow goes as a straight line on the left from top to bottom. It’s often considered as a "good" or "basic" scenario. All diverts from it goes to right. Many diverts often are quite simple - for example it can be error workaround and exit.
For example you have a function whether number is positive:
func IsPositive(n int) bool {
if n <= 0 {
return false
}
return true
}
You may trace a main execution line on the left and catch keywords IsPositive
below check digression if ...
and at the bottom return true
. As you can see we do not use else
. We got it “for free” (without visual overloading) as a sole remaining option in our program. I can say functions structured this way require else
quite rarely. Also you won’t find it very often keyword on standard code.
Upvotes: 0
Reputation: 79734
The rule is: return
when you're done processing, to prevent further processing.
In your case, a return
is not necessary, because there is no further processing in your function. If you had further logic, though, you would want to return:
func SomeHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
if thisThing != thatThing {
log.Print("thisThing not equal to thatThing - redirecting")
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return // <-- is this necessary?
}
w.Header().Add("Content-Type", "application/json")
// ... add a normal response
}
Without a return in this case, you'll send the headers to initiate a redirect, then you'll also send a normal JSON response. That is obviously not what you want, so the return
is needed.
The astute reader will note that there would be other ways to accomplish this type of control flow. An else
would be an option:
func SomeHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
if thisThing != thatThing {
log.Print("thisThing not equal to thatThing - redirecting")
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
} else {
w.Header().Add("Content-Type", "application/json")
// ... add a normal response
}
}
However, as your conditions grow in complexity, a return
is often going to be the most readable method. But it is ultimately a style choice at that point.
Upvotes: 5