doufei16736 2015-07-17 10:58
浏览 50
已采纳

模板文件中的Golang重定向功能失败

As the golang documentation states, a template function has to have at least 1 return parameter, so I think I can rule out template functions already.

So I thought I could just create the function directly on the Content model, but I guess not?

I think the markup below is pretty self explaining (index.tmpl file in root folder):

{{$request := .Request}}
{{$response := .Response}}
{{if eq $request.Method "POST"}}
    {{.Redirect "page1" 301}}
{{end}}

<!DOCTYPE html>
<html>
  <head>
    <title>{{.Title | title}}</title>
  </head>
  <body>
    <h1>{{.Title}}</h1>
    {{.Body}}
    <p>{{.ContentType}}</p>
    <p>{{$request}}</p>
    <p>{{lol}}</p>
    <form method="POST">
        <input type="text" name="lolcat"/>
        <input type="submit" value="submit"/>
    </form>
  </body>
</html>

This is kinda equivalent to how one would do it in ASP.Net/Razor, but it doesn't work.

The rest of the code is here http://play.golang.org/p/LMKdflA9RS

To test the program locally you need to have:

main.go
index.tmpl
page1.tmpl (just use the same as index.tmpl)

What am I doing wrong, and how can this be achieved? :-)

Solution:

http://play.golang.org/p/b2I_uzjiSH

Thanks to Ainar-G!

  • 写回答

1条回答 默认 最新

  • duanqi5114 2015-07-17 11:22
    关注

    Logic like this should go into handlers. Templates are for presenting data only. They are not designed to be anything more. Any decisions about what and how to render should be done in the handler code.

    With that in mind, here is how you could do that: http://play.golang.org/p/Md5A54rLm7.

    You can't write directly to w because this will cause it to set response code to 200. You should also register the redirect function inside a wrapper because all template functions must return one or two (with error) values. Again, just because you can, it doesn't mean you should.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集