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.