示例#1
0
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	// for now: ignore options and favicon
	if r.Method == "OPTIONS" || r.URL.Path == "/favicon.ico" {
		return
	}

	//handle static mapping
	if r.Method == "GET" && strings.HasPrefix(r.URL.Path, "/static/") {
		m.static.ServeHTTP(w, r)
		return
	}

	for _, route := range m.routes {
		if route.method == r.Method {
			path := util.SliceString(r.URL.Path, '/')
			if pathVars, ok := match(path, route.path); ok {
				ctx := m.ctx.get(w, r)
				ctx.SetPathVars(pathVars)
				route.handle(w, r, ctx)
				return
			}
		}
	}
	return
}
示例#2
0
func NewTemplateStore(development bool) *TemplateStore {
	t := &TemplateStore{
		templates: make(map[string]*template.Template),
		bufpool: &bufferPool{
			ch: make(chan *bytes.Buffer, 64),
		},
		TemplateDir: "templates/",
		Development: development,
		funcs: template.FuncMap{
			"title": strings.Title,
			"safe":  func(html string) template.HTML { return template.HTML(html) },
			"add":   func(a, b int) int { return a + b },
			"sub":   func(a, b int) int { return a - b },
			"decr":  func(a int) int { return a - 1 },
			"incr":  func(a int) int { return a + 1 },
			"split": strings.Split,
			"map":   func(a map[string]string, b string) interface{} { return a[b] },
			"pretty": func(v interface{}) string {
				b, err := json.MarshalIndent(v, "", "\t")
				if err != nil {
					log.Println(err)
				}
				return string(b)
			},
			"date": func(d string) string {
				ds := util.SliceString(d, '-')
				return fmt.Sprintf("%s/%s/%s", ds[1], ds[2], ds[0])
			},
		},
	}
	t.Load()
	return t
}
示例#3
0
func (m *Mux) handle(method, path string, handler controller) {
	m.routes = append(m.routes, &route{method, util.SliceString(path, '/'), handler})
}