从Go中的子功能关闭/返回ResponseWriter

时间:2018-07-25 16:00:46

标签: go web handler

我是Go和构建Web应用程序的新手。我的处理程序的示例如下:

func getAllPostsHandler(w http.ResponseWriter, r *http.Request) {
    var posts []Post

    dbSesstion := context.Get(r, "database").(*mgo.Session)
    err := dbSesstion.DB(dbsett.Name).C(dbsett.Collection).Find(nil).All(&posts)
    if err != nil {
        log.Print("error: ", nil)
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    err = json.NewEncoder(w).Encode(posts)
    if err != nil {
        log.Print("error: ", nil)
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    w.WriteHeader(http.StatusOK)
}

我的处理程序有很多重复的错误检查,如下所示:

if err != nil {
    log.Print("error: ", nil)
    w.WriteHeader(http.StatusInternalServerError)
    return
}

我想创建一个函数,该函数检查错误,打印日志,在必要时编写响应编写器,然后返回(不仅返回到处理程序),而且停止所有其他响应编写并返回处理程序本身。有可能这样做吗?我正在考虑恐慌,但有一些事情告诉我这不是正确的方法。

1 个答案:

答案 0 :(得分:-1)

您不能从最内层逃避最外层的功能,但可以通过反转控制流至少压缩一点代码

err := dbSesstion.DB(dbsett.Name).C(dbsett.Collection).Find(nil).All(&posts)
if err == nil {
    err = json.NewEncoder(w).Encode(posts)
    if err == nil {
        err = somethingelse()
        if err == nil {
            w.WriteHeader(http.StatusOK)
            return //successfully
        }
    }
}
log.Print("error: ", nil)
w.WriteHeader(http.StatusInternalServerError)