重定向后停止代码执行

  • 本文关键字:代码 执行 重定向 go
  • 更新时间 :
  • 英文 :

//main.go
func (self *GoodsController) GoodsEditGet(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    tmpID, ok := vars["id"]
    sess := session.Instance(w, r)
    if !ok {
        tpl.Error("Invalid goods id")
    }
    id, _ := strconv.ParseInt(tmpID, 10, 64)
    goods, err := service.NewGoodsService(w, r).GetGoodsDetail(id)
    if err != nil {
        //This utility function will not stop the rest of the code being executed
        util.RedirectWithMessage(w, r, err.Error(), "/system/inventory/goods")
    }
    //This line will be executed even though the above line producing error
    goodsUom, err := service.NewGoodsService(w, r).GetGoodsUom(id)
    if err != nil {
        util.RedirectWithMessage(w, r, err.Error(), "/system/inventory/goods")
    }
}
//package utility
func RedirectWithMessage(w http.ResponseWriter, r *http.Request, errMsg string, redirect string) {
    sess := session.Instance(w, r)
    sess.FlashError(errMsg)
    sess.FlashForm(r)
    sess.Save(r, w)
    http.Redirect(w, r, redirect, http.StatusFound)
    return
}

我可以知道如何在调用函数 RedirectWithMessage之后停止执行代码的其余部分?

return放在该函数的末尾没有执行的代码

我在Golang中寻找相当于PHP版本的重定向:

fuunction foo($location){
  header(“Location : $location”);
  exit();
}
 foo("/bar"):
 echo "blah"; //this will not be executed

编辑过度狂热的原因。

是的,我完全意识到我可以在拨打RedirectWithMessage之后放置return语句。我只是不想用return语句混乱我的代码。我只是想知道有更好的解决方案吗?我可以实现像我显示的PHP代码一样的行为吗?

我很想给您panic defer的方式,并警告您不要使用它,但是我意识到更改API可能会更好。

您可以将函数的主要逻辑集中在函数的主要逻辑中,并将错误返回给呼叫者,并要求呼叫者以所需的方式处理错误,例如重定向,日志等。

func (self *GoodsController) GoodsEditGet(w http.ResponseWriter, r *http.Request) {
    err:=self.goodsEditGet(w,r)
    if err!=nil { //Note 1
        util.RedirectWithMessage(w, r, err.Error(), "/system/inventory/goods")
    }
}
func (self *GoodsController) goodsEditGet(w http.ResponsWriter, r *http.Request) {
    vars := mux.Vars(r)
    tmpID, ok := vars["id"]
    sess := session.Instance(w, r)
    if !ok {
        tpl.Error("Invalid goods id")
    }
    id, _ := strconv.ParseInt(tmpID, 10, 64)
    goods, err := service.NewGoodsService(w, r).GetGoodsDetail(id)
    if err != nil {
        //This utility function will not stop the rest of the code being executed
        return err //Note 2
    }
    goodsUom, err := service.NewGoodsService(w, r).GetGoodsUom(id)
    if err != nil {
        return err
    }
    return nil
}

注意1:您可能想处理更多指定的错误,而不仅仅是与零和非nil打交道。在这种情况下,类型断言可能是一个好主意。

注2:您可能想包装错误。您可以尝试github/pkg/errors,这是一个很好的软件包,处理由Dave Cheney撰写的Erros。

注释3:建议使用self作为接收器名称,因为它很模棱两可。

最新更新