mercredi 25 juillet 2018

Close/return ResponseWriter from child function in Go

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.




Aucun commentaire:

Enregistrer un commentaire