dongyao1895 2018-07-25 16:00
浏览 100

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

I am new to Go and building web apps. An example of my handler is something like this:

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)
}

My handlers have a lot of repeating error checking like this:

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

I want to make a function, which checks for error, print logs, write the response writer if neccessary, and return, but not only to the handler, but to stop all other response writings and return the handler itself. Is it possible to do so? I am thinking about panicing, but something tells me that its not the right way.

  • 写回答

1条回答 默认 最新

  • dthswrp84966 2018-07-25 17:25
    关注

    You can't escape outermost function from innermost but you can at least compact code a bit by inverting control flow

    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) 
    
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码