我对http处理程序和处理错误或重定向等问题有点困惑.
例如,如果由于某些条件检查我必须重定向,我应该执行以下操作:
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?
    }
 }
Run Code Online (Sandbox Code Playgroud)
    规则是:return当您完成处理时,以防止进一步处理.
在您的情况下,a 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
 }
Run Code Online (Sandbox Code Playgroud)
在这种情况下没有返回,您将发送标头以启动重定向,然后您还将发送正常的JSON响应.这显然不是你想要的,所以return需要它.
精明的读者会注意到,还有其他方法可以实现这种类型的控制流程.一个else将是一种选择:
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
    }
 }
Run Code Online (Sandbox Code Playgroud)
但是,随着您的条件越来越复杂,a return通常会成为最易读的方法.但在这一点上,它最终是一种风格选择.