Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
with
46 additions
and 47 deletions.
- +3 −17 handlers.go
- +3 −30 main.go
- +28 −0 template.go
- +2 −0 templates/index.html
- +10 −0 templates/login.html
@@ -3,32 +3,9 @@ package main | ||
import ( | ||
"code.google.com/p/gorilla/pat" | ||
"fmt" | ||
"html/template" | ||
"labix.org/v2/mgo" | ||
"net/http" | ||
"net/url" | ||
"os" | ||
"path/filepath" | ||
) | ||
|
||
var funcs = template.FuncMap{ | ||
"reverse": reverse, | ||
} | ||
|
||
func parseTemplate(files ...string) *template.Template { | ||
//create a new template named after the first file in the list and add | ||
//the function map to it | ||
name := filepath.Base(files[0]) | ||
t := template.New(name).Funcs(funcs) | ||
|
||
//parse the files into the template and panic on errors | ||
t = template.Must(t.ParseFiles(files...)) | ||
return t | ||
} | ||
|
||
var index = parseTemplate( | ||
"templates/_base.html", | ||
"templates/index.html", | ||
) | ||
|
||
func reverse(name string, things ...interface{}) string { | ||
@@ -51,18 +28,14 @@ var router *pat.Router | ||
|
||
func main() { | ||
var err error | ||
u := os.Getenv("DATABASE_URL") | ||
parsed, err := url.Parse(u) | ||
if err != nil { | ||
panic(err) | ||
} | ||
database = parsed.Path[1:] | ||
session, err = mgo.Dial(u) | ||
session, err = mgo.Dial(os.Getenv("DATABASE_URL")) | ||
if err != nil { | ||
panic(err) | ||
} | ||
database = session.DB("").Name | ||
This comment has been minimized.
zeebo
Author
Owner
|
||
|
||
router = pat.New() | ||
router.Add("GET", "/login", handler(loginForm)).Name("login") | ||
router.Add("GET", "/", handler(hello)).Name("index") | ||
router.Add("POST", "/sign", handler(sign)).Name("sign") | ||
|
||
@@ -0,0 +1,28 @@ | ||
package main | ||
|
||
import ( | ||
"html/template" | ||
"path/filepath" | ||
) | ||
|
||
var cachedTemplates = map[string]*template.Template{} | ||
|
||
var funcs = template.FuncMap{ | ||
"reverse": reverse, | ||
} | ||
|
||
func T(name string) *template.Template { | ||
if t, ok := cachedTemplates[name]; ok { | ||
return t | ||
} | ||
|
||
t := template.New("_base.html").Funcs(funcs) | ||
|
||
t = template.Must(t.ParseFiles( | ||
"templates/_base.html", | ||
filepath.Join("templates", name), | ||
)) | ||
cachedTemplates[name] = t | ||
|
||
return t | ||
} | ||
This comment has been minimized.
zeebo
Author
Owner
|
@@ -0,0 +1,10 @@ | ||
{{ define "title" }}Guestbook - Login{{ end }} | ||
|
||
{{ define "content" }} | ||
<h1>Login</h1> | ||
<form action="{{ reverse "login" }}" method="POST"> | ||
<p>Username: <input type="text" name="username"></p> | ||
<p>Password: <input type="password" name="password"></p> | ||
<p><button>Login</button></p> | ||
</form> | ||
{{ end }} |
Here we use the new T function for compiling the index template on the fly.