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!
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.