Web.go我如何进行HTTP重定向?

huangapple go评论88阅读模式
英文:

Web.go How can I do http redirections?

问题

我正在使用web.go编写一个小应用程序,其中包含一个用于提供表单的函数。如果表单无效,用户将被重定向到同一页:

func mypage(ctx *web.Context) {
     if ctx.Request.Method == "GET" {
         // 显示表单
     } else if ctx.Request.Method == "POST" {
        // 如果表单无效,则重定向:
        ctx.Request.Method = "GET"
        http.Redirect(ctx.ResponseWriter, 
                      ctx.Request, "/mypage", http.StatusNotAcceptable)
        return
     }
}

这个代码是可以工作的,但有一个问题,当表单无效时,它首先显示一个带有文本“Not Acceptable”的页面,该页面链接到“/mypage”。我该如何使其在表单无效的情况下直接跳转到“/mypage”?我怀疑这与“http.StatusNotAcceptable”有关,但我不知道应该用什么替换它。

英文:

I am writing a small app using web.go with a function that serves a form. If the form is not valid, user will be redirected to the same page:

func mypage(ctx *web.Context) {
     if ctx.Request.Method == "GET" {
         // show the form
     } else if ctx.Request.Method == "POST" {
        // redirection if the form is not valid:
        ctx.Request.Method = "GET"
        http.Redirect(ctx.ResponseWriter, 
                      ctx.Request, "/mypage", http.StatusNotAcceptable)
        return
     }
}

This works, with one caveat that when the form is not valid, it first shows a page with the text "Not Acceptable" that is liked to /mypage. How can I make it to go directly to /mypage in case the form is not valid? I suspect that it is related to http.StatusNotAcceptable but I don't know what I should replace it with.

答案1

得分: 1

所以结果证明这很容易 Web.go我如何进行HTTP重定向?

ctx.Request.Method = "GET"
mypage(ctx)

不需要使用http.Redirect。重要的部分是在调用mypage(ctx)之前首先将Method更改为GET

英文:

So turns out it was easy Web.go我如何进行HTTP重定向?

ctx.Request.Method = "GET"
mypage(ctx)

No need for http.Redirect. The important part is to change the Method to GET first, before calling mypage(ctx).

huangapple
  • 本文由 发表于 2013年6月6日 00:41:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/16945429.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定