登录
首页 >  Golang >  Go问答

可以在 Go 中执行模板后重定向页面的新 URL 吗?

来源:stackoverflow

时间:2024-03-14 10:24:25 319浏览 收藏

大家好,今天本人给大家带来文章《可以在 Go 中执行模板后重定向页面的新 URL 吗?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我遇到的问题与这篇文章几乎相同,但那里的答案并没有真正让我清楚地了解如何解决它。

我想在用户提交表单后将数据发送到新页面,因此您自然会使用 html/template 包中的 ExecuteTemplate

这会将页面重定向到包含数据的新页面,但 URL 保持不变。

这意味着,如果您使用 ExecuteTemplatehttp://example.com/login 上提交表单,您将转到包含数据的新页面,但其 URL 仍显示 http://example.com/login。 p>

我尝试将 http.Redirect(w, r, "/newPage", http.StatusSeeOther) 放在 ExecuteTemplate 代码后面,但结果是相同的,这意味着该页面移动到带有数据的新页面,但网址仍然是 http://example.com/login 而不是 http://example.com/newPage。有没有办法解决这个问题?

我使用的是 Go 版本 1.13.3。


解决方案


您永远不必在重定向响应中显示模板。这也没有任何意义。

有两种方法可以达到您想要的效果。

带重定向

这是您原来的工作流程。您应该将这个表单页面 http://example.com/login 分为 3 个步骤:

  1. 用户打开登录页面。然后您将显示正常的登录表单。
  2. 用户提交登录表单。您收到登录表单提交的内容,因此您会将用户重定向到带有标志和数据的页面。
  3. 用户已重定向。您发现需要显示带有数据的表单/页面,您显示了表单以外的内容。

但是你如何确定你已经达到了(3)呢?一种方法是在重定向时将数据附加到 url。假设我们读取“step=2”的 get 参数:

func loginpage(w http.responsewriter, r *http.request) {
  if r.url.query().get("step") == "2" {
    // show the form / page described in (3) above.
    // ...
    return
  }

  // suppose your form method is post
  if r.method == "post" {
    if err := r.parseform(); err != nil {
      // handle parse error
    }

    // handle form submission normally
    // also somehow store the form submitted value for later use
    // ...
    // ...

    // now redirect to the url, as described in (2)
    http.redirect(w, r, "/login?step=2")
    return
  }

  // handle the normal form display as described in (1)
  // do your executetemplate
}

没有重定向

或者,您也可以在不进行任何重定向的情况下执行此操作。只需通过两个步骤来思考:

  1. 用户打开登录页面。然后您将显示正常的登录表单。
  2. 用户提交登录表单。您发现您需要显示带有数据的表单/页面,您显示了表单以外的其他内容。没有重定向
func loginPage(w http.ResponseWriter, r *http.Request) {
  // suppose your form method is POST
  if r.Method == "POST" {
    if err := r.ParseForm(); err != nil {
      // handle parse error
    }

    // handle form submission normally
    // also somehow store the form submitted value for later use
    // ...
    // ...

    // handle the special form / page display as described in (2)
    // do your ExecuteTemplate
    // ...
    // ...

    return
  }

  // handle the normal form display as described in (1)
  // do your ExecuteTemplate
}

理论要掌握,实操不能落!以上关于《可以在 Go 中执行模板后重定向页面的新 URL 吗?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>