Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 11eab9ed47
Fetching contributors…

Cannot retrieve contributors at this time

file 97 lines (82 sloc) 2.213 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
package goldorak

import (
"mustache"
"log"
"strings"
"web"
)

type Action struct {
responded bool
layout *Action
template string
locals map[string]string
context *web.Context
}

var defaultLayout *Action = nil

func ctxHandler(handler func(*Action, []string)) (func(ctx *web.Context)) {
f := func(ctx *web.Context) {
action := NewAction()
action.layout = defaultLayout
action.context = ctx
params := strings.Split(ctx.Request.URL.Path[1:], "/", 0)
handler(&action, params)
if !action.responded {
action.responded = true
ctx.StartResponse(200)
ctx.WriteString(action.Render(action.locals))
}
}
return f
}

// TODO not found page?
// TODO func Restful() ?
// Note for myself: the last route is the most important one (it's the opposite of Rails)
func Get(route string, handler func(*Action, []string)) {
web.Get(route, ctxHandler(handler))
}

func Post(route string, handler func(*Action, []string)) {
web.Post(route, ctxHandler(handler))
}

func DefaultLayout(handler func(*Action)) {
action := NewAction()
handler(&action)
defaultLayout = &action
}

func NewAction() Action {
return Action{false, nil, "", make(map[string]string), nil}
}

func (this *Action) Param(key string) []string {
return this.context.Request.Params[key]
}

func (this *Action) Template(template string) {
this.template = template
}

func (this *Action) Assign(key string, value string) {
this.locals[key] = value
}

func (this *Action) Layout(handler func(*Action)) {
action := NewAction()
handler(&action)
this.layout = &action
}

func (this *Action) NoLayout() {
this.layout = nil
}

func (this *Action) Render(context interface{}) string {
log.Stdoutf("Rendering %s", this.template)
filename := GetConfig("templates") + "/" + this.template + ".mustache"
output, err := mustache.RenderFile(filename, context)
if err != nil {
log.Stderrf("Error on rendering %s", filename, err)
return "" // TODO error page
}
if this.layout != nil {
output = this.layout.Render(map[string]string{"yield": output})
}
return output
}

func (this *Action) Redirect(path string) {
this.responded = true
url := "http://" + GetConfig("domain") + path
this.context.Redirect(302, url)
}
Something went wrong with that request. Please try again.