コード例 #1
0
func (self *Server) LoadTemplates() error {
	if err := pongo.Initialize(); err != nil {
		return nil
	}

	return filepath.Walk(self.TemplatePath, func(filename string, info os.FileInfo, err error) error {
		log.Debugf("File in template path: %s (err: %v)", filename, err)

		if err == nil {
			if info.Mode().IsRegular() && !strings.HasPrefix(path.Base(filename), `_`) {
				ext := path.Ext(filename)
				key := strings.TrimSuffix(strings.TrimPrefix(filename, path.Clean(self.TemplatePath)+`/`), ext)

				if _, ok := self.Templates[key]; !ok {
					var tpl engines.ITemplate

					switch ext {
					case `.pongo`:
						tpl = pongo.New()
					default:
						return nil
					}

					tpl.SetTemplateDir(self.TemplatePath)

					log.Debugf("Load template at %s: %T: [%s] %s", filename, tpl, key, tpl.GetTemplateDir())

					if err := tpl.Load(key); err == nil {
						self.Templates[key] = tpl
					} else {
						log.Warnf("Error loading template '%s': %v", filename, err)
						return nil
					}
				} else {
					log.Warnf("Cannot load template '%s', key was already loaded", filename)
				}
			}
		}

		return nil
	})
}
コード例 #2
0
func (self *Server) Serve() error {
	self.router = httprouter.New()

	self.RoutePrefix = strings.TrimSuffix(self.RoutePrefix, `/`)

	self.router.GET(fmt.Sprintf("%s/*path", self.RoutePrefix), func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		routePath := params.ByName(`path`)
		tplKey := routePath
		var tpl engines.ITemplate

		if tplKey == `/` || tplKey == `` {
			tplKey = `/index`
		}

		parts := strings.Split(tplKey, `/`)
		parts = parts[1:len(parts)]

		for i, _ := range parts {
			key := strings.Join(parts[0:len(parts)-i], `/`)
			// log.Infof("Trying: %s", key)

			if t, ok := self.Templates[key+`/index`]; ok {
				tpl = t
				break
			} else if t, ok := self.Templates[key]; ok {
				tpl = t
				break
			}
		}

		//  template was not found, attempt to load the index template
		if tpl == nil {
			if t, ok := self.Templates[`index`]; ok {
				tpl = t
			}
		}

		if tpl != nil {
			routeBindings := self.GetBindings(req.Method, routePath, req)
			allParams := make(map[string]interface{})
			allRouteParams := make(map[string]interface{})

			for _, binding := range routeBindings {
				for k, v := range binding.ResourceParams {
					allParams[k] = v
				}

				for k, v := range binding.RouteParams {
					allRouteParams[k] = v
				}
			}

			payload := map[string]interface{}{
				`route`:        params.ByName(`path`),
				`route_params`: allRouteParams,
				`params`:       allParams,
			}

			bindingData := make(map[string]interface{})

			for key, binding := range routeBindings {
				if data, err := binding.Evaluate(req, params); err == nil {
					bindingData[key] = data
				} else {
					log.Errorf("Binding '%s' failed to evaluate: %v", key, err)
				}
			}

			payload[`data`] = bindingData

			// log.Debugf("Data for %s\n---\n%+v\n---\n", routePath, payload)

			if err := tpl.Render(w, payload); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}

		} else {
			http.Error(w, fmt.Sprintf("Template '%s' not found", tplKey), http.StatusNotFound)
		}
	})

	staticHandler := negroni.NewStatic(http.Dir(self.StaticPath))

	if self.RoutePrefix != DEFAULT_ROUTE_PREFIX {
		staticHandler.Prefix = self.RoutePrefix
	}

	self.server = negroni.New()
	self.server.Use(negroni.NewRecovery())
	self.server.Use(staticHandler)
	self.server.UseHandler(self.router)

	self.server.Run(fmt.Sprintf("%s:%d", self.Address, self.Port))
	return nil
}