Golang:如何重定向到一个网址 [英] Golang: how to redirect to a url

查看:1339
本文介绍了Golang:如何重定向到一个网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在从上一页收集数据后向客户显示另一页。但是我无法在服务器端重定向新的URL。这里是我的逻辑:


  1. 使用POST动作提交用户输入到服务器;
  2. 服务器运行函数saveChoice()将用户输入保存到数据库中;
  3. 保存用户输入后,服务器向客户端发送一个新的URL;
  4. 到时候客户端获取新的URL,服务器读取数据库并获取保存的数据

我被困在步骤3(这里是流的示例):

  type Stuff struct {
List [] string
}

func checkcheck(w http.ResponseWriter,r * http.Request){
sinfo:=东西{
列表:some_slice
}

t, err:= template.New()。解析(tpl_ds)
checkErr(err)
err = r.ParseForm()
checkErr(err)
err = t。执行(w,sinfo)
checkErr(err)

如果r.Method ==POST{
saveChoice(r.Form [choices])
/ *步骤3:让用户打开另一个URL * /
}
}

以下是模板:

 < HTML> 
< script>
$(function(){
$('form')。on('submit',function(e){
e.preventDefault();
$ .ajax( {
type:'post',
data:$('form')。serialize(),
});
});
});
< / script>
< body>
< form method =POST>
{{range .List}}
< input type =checkboxname =choicesvalue ={{。}}> <跨度> {{}}< /跨度><峰; br>
{{end}}
< input type =submitvalue =Submit>
< / form>
< / body>
< / html>

我可以知道如何重定向到新页面吗?

ps如果我把URL放在按钮上,那么服务器不会运行saveChoice()。

谢谢!

解决方案

http状态303是适当的响应。所以重定向请求。

  if r.Method ==POST{
saveChoice(r.Form [choices])
http.Redirect(w,r,newUrl,http.StatusSeeOther)
}

如果你的 newUrl 应该返回一个合适的html页面给浏览器,你不需要使用ajax。使用html表单。

 < form action =/ postHandlermethod =post> 
{{range .List}}
< input type =checkboxname =choicesvalue ={{。}}> <跨度> {{}}< /跨度><峰; br>
{{end}}
< input type =submitvalue =Submit>
< / form>

注意 action 的形式被定义为 / postHandler 。把运行你的 saveChoice 函数的端点的名称放在那里。

所以要避免 http:multiple response.WriteHeader calls error you get get this code。

  func checkcheck(w http .ResponseWriter,r * http.Request){
if r.Method ==GET{
sinfo:= Stuff {
List:some_slice
}

t,err:= template.New()。解析(tpl_ds)
checkErr(err)
err = r.ParseForm()
checkErr(err)
err = t.Execute(w,sinfo)
checkErr(err)
}

if r.Method ==POST{
saveChoice(r.Form [choices])
http.Redirect(w,r,newUrl,http.StatusSeeOther)
}
}

否则,服务器将尝试呈现表单和重定向的url,这将导致对响应编写器进行多次调用。


I would like to show client another page after data has been collected from previous page. But I have trouble redirect the new URL on the server side. Here is my logic:

  1. submit user input with POST action to server;
  2. server run function saveChoice() to save user input into a database;
  3. After user input is saved, server send a new URL to client;
  4. By the time the client GET the new URL, server reads the database and get saved data out

And I am stuck on step 3 (here is an example of the flow):

type Stuff struct{
    List []string
}

func checkcheck(w http.ResponseWriter, r *http.Request) {
    sinfo := Stuff{
        List: some_slice
    }

    t, err := template.New("").Parse(tpl_ds)
    checkErr(err)
    err = r.ParseForm()
    checkErr(err)
    err = t.Execute(w, sinfo)
    checkErr(err)

    if r.Method == "POST" {
        saveChoice(r.Form["choices"])
        /* step 3: make user open another URL */
    }
}

And here is the template:

<html>
<script>
  $(function () {
    $('form').on('submit', function (e) {
      e.preventDefault();
      $.ajax({
        type: 'post',
        data: $('form').serialize(),
      });
    });
  });
</script>
<body>
  <form method="POST">
    {{range .List}}
        <input type="checkbox" name="choices" value="{{.}}"> <span>{{.}}</span><br>
    {{end}}
    <input type="submit" value="Submit">
  </form>
</body>
</html>

May I know how I can redirect to a new page?

p.s. If I put URL on button, then server is not going to run saveChoice()

Thanks!

解决方案

The http status 303 is the appropriate response here. So redirect the request with it.

if r.Method == "POST" {
    saveChoice(r.Form["choices"])
    http.Redirect(w, r, newUrl, http.StatusSeeOther)
}

And if your newUrl is supposed to return a proper html page to the browser, you don't need to use ajax. Use an html form.

<form action="/postHandler" method="post">
   {{range .List}}
    <input type="checkbox" name="choices" value="{{.}}"> <span>{{.}}</span><br>
   {{end}}
    <input type="submit" value="Submit">
</form>

Notice action of the form is defined as /postHandler. Put the name of the endpoint that runs your saveChoice function there.

So to avoid http: multiple response.WriteHeader calls error you get use this code.

  func checkcheck(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
      sinfo := Stuff{
        List: some_slice
      }

      t, err := template.New("").Parse(tpl_ds)
      checkErr(err)
      err = r.ParseForm()
      checkErr(err)
      err = t.Execute(w, sinfo)
      checkErr(err)
    }

    if r.Method == "POST" {
        saveChoice(r.Form["choices"])
        http.Redirect(w, r, newUrl, http.StatusSeeOther)
    }
  }

Otherwise, the server attempts to render both the form and the redirected url which will result in mutiple calls to the response writer.

这篇关于Golang:如何重定向到一个网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆