drqefnd544707688 2017-11-22 07:33
浏览 28
已采纳

HTTP处理程序-什么时候应该使用return?

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?
    }
 }
  • 写回答

2条回答 默认 最新

  • dongyanju1094 2017-11-22 09:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用