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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。