Example #1
0
func watchAndParseTemplates() {

	templatesDir := utils.FindDir("web/templates")
	l4g.Debug(utils.T("web.parsing_templates.debug"), templatesDir)
	var err error
	if Templates, err = template.ParseGlob(templatesDir + "*.html"); err != nil {
		l4g.Error(utils.T("web.parsing_templates.error"), err)
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		l4g.Error(utils.T("web.create_dir.error"), err)
	}

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				if event.Op&fsnotify.Write == fsnotify.Write {
					l4g.Info(utils.T("web.reparse_templates.info"), event.Name)
					if Templates, err = template.ParseGlob(templatesDir + "*.html"); err != nil {
						l4g.Error(utils.T("web.parsing_templates.error"), err)
					}
				}
			case err := <-watcher.Errors:
				l4g.Error(utils.T("web.dir_fail.error"), err)
			}
		}
	}()

	err = watcher.Add(templatesDir)
	if err != nil {
		l4g.Error(utils.T("web.watcher_fail.error"), err)
	}
}
Example #2
0
func watchAndParseTemplates() {

	templatesDir := utils.FindDir("web/templates")
	l4g.Debug("Parsing templates at %v", templatesDir)
	var err error
	if Templates, err = template.ParseGlob(templatesDir + "*.html"); err != nil {
		l4g.Error("Failed to parse templates %v", err)
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		l4g.Error("Failed to create directory watcher %v", err)
	}

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				if event.Op&fsnotify.Write == fsnotify.Write {
					l4g.Info("Re-parsing templates because of modified file %v", event.Name)
					if Templates, err = template.ParseGlob(templatesDir + "*.html"); err != nil {
						l4g.Error("Failed to parse templates %v", err)
					}
				}
			case err := <-watcher.Errors:
				l4g.Error("Failed in directory watcher %v", err)
			}
		}
	}()

	err = watcher.Add(templatesDir)
	if err != nil {
		l4g.Error("Failed to add directory to watcher %v", err)
	}
}
Example #3
0
func (engine *Engine) LoadHTMLGlob(pattern string) {
	if IsDebugging() {
		debugPrintLoadTemplate(template.Must(template.ParseGlob(pattern)))
		engine.HTMLRender = render.HTMLDebug{Glob: pattern}
	} else {
		templ := template.Must(template.ParseGlob(pattern))
		engine.SetHTMLTemplate(templ)
	}
}
Example #4
0
func startServer(port string) {
	manager = session.NewSessionManager(nil)

	manager.OnStart(func(session *session.Session) {
		l.Debug("Session Manager: Started a new session.\n")
	})
	manager.OnEnd(func(session *session.Session) {
		l.Debug("Session Manager: Destroyed a session.\n")
	})
	manager.SetTimeout(10)

	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static/"))))
	http.HandleFunc("/data", DataHandler)
	http.HandleFunc("/", IndexHandler)
	http.HandleFunc("/login", LoginHandler)
	var e error

	t, e = template.ParseGlob("web/templates/*.tmpl")

	if e != nil {
		l.Fatal("Unable to parse templates: %s\n", e.Error())
	}

	e = http.ListenAndServe(port, nil)

	if e != nil {
		l.Fatal("Unable to start embeeded webserver: %s\n", e.Error())
	}
}
Example #5
0
func init() {
	tpl, _ = template.ParseGlob("*.html")
	http.HandleFunc("/", main)

	//serve the css files in a file server instead of uploading it to gcs and querying it.
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css"))))
}
func main() {
	tpl = template.Must(template.ParseGlob("templates/*.gohtml"))

	f, err := os.OpenFile("logfile.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0664)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	log.SetOutput(f)

	client, err = as.NewClient("127.0.0.1", 3000)
	if err != nil {
		panic(err)
	}
	defer client.Close()

	router := httprouter.New()
	router.GET("/", index)
	router.GET("/login", loginPage)
	router.POST("/login", login)
	router.GET("/logout", logout)
	router.GET("/create", createPage)
	router.POST("/create", create)
	err = http.ListenAndServe(":9000", router)
	if err != nil {
		panic(err)
	}
}
Example #7
0
func ParseGlob(pattern string) (Template, error) {
	if Debug {
		return (&reloadTemplate{}).ParseGlob(pattern)
	}
	t, err := htmlTmpl.ParseGlob(pattern)
	return &instantTemplate{t}, err
}
Example #8
0
func adminUsersHandler(w http.ResponseWriter, r *http.Request, admin Location) {
	isAuth(w, r, admin, "admin")
	if r.Method == "POST" {
		var user httpauth.UserData
		user.Username = r.PostFormValue("username")
		user.Email = r.PostFormValue("email")
		password := r.PostFormValue("password")
		user.Role = r.PostFormValue("role")
		if err := aaa.Register(w, r, user, password); err != nil {
			// maybe something
		}
	}

	if user, err := aaa.CurrentUser(w, r); err == nil {
		type data struct {
			User  httpauth.UserData
			Roles map[string]httpauth.Role
			Users []httpauth.UserData
			Msg   []string
		}
		messages := aaa.Messages(w, r)
		users, err := backend.Users()
		if err != nil {
			panic(err)
		}
		d := data{User: user, Roles: roles, Users: users, Msg: messages}
		var templates = template.Must(template.ParseGlob("admin/templates/*"))
		t_err := templates.ExecuteTemplate(w, "manage-accounts.html", d)
		if t_err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}
Example #9
0
// Wraps other http handlers. Creates context object, recovers from panics, etc.
func WrapHandlerImpl(fn AppHandlerFunc, parseForm bool) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c := &Context{}

		// See http://blog.golang.org/2010/08/defer-panic-and-recover.html.
		defer func() {
			if data := recover(); data != nil {
				c.Aec().Errorf(fmt.Sprint(data))
				ServeError(w, data)
			}
		}()

		// Initialize the request context object.
		c.SetAec(appengine.NewContext(r))
		CheckError(ReadSession(r, c))
		if msg, err := ConsumeFlash(w, r); err != nil && err != http.ErrNoCookie {
			ServeError(w, err)
			return
		} else {
			c.SetFlash(msg)
		}

		if parseForm {
			CheckError(r.ParseForm())
		}

		if appengine.IsDevAppServer() {
			tmpl = template.Must(template.ParseGlob("templates/*.html"))
			text_tmpl = text_template.Must(text_template.ParseGlob("templates/*.txt"))
		}
		fn(w, r, c)
	}
}
Example #10
0
// set everything up.
func init() {
	tpl = template.Must(template.ParseGlob("*.html"))
	resourceHandler("css")
	resourceHandler("img")
	resourceHandler("photos")
	http.HandleFunc("/", mainPage)
}
Example #11
0
func actionHome(w http.ResponseWriter, req *http.Request) {

	var templActionHome *template.Template = template.Must(
		template.ParseGlob("templates/home/*.html"))

	lay := getLayoutTemplates()
	wr := &HtmlContainer{}

	// templActionHome.Funcs(template.FuncMap{"len": Len})
	data := HtmlAssigner{
		"List": getEntryList("", 10),
		"Test": "Test",
	}

	err := templActionHome.Execute(wr, data)
	if err != nil {
		fmt.Errorf("%v", err)
	}

	lay.New("title").Parse("Najnowsze wpisy - " + config.GetStringDef("page", "title", ""))

	err = lay.Execute(w, wr.getHtml())
	if err != nil {
		fmt.Errorf("%v", err)
	}
}
Example #12
0
func loadTemplates() (templates *template.Template, err error) {
	if !*devMode && t != nil {
		return t, nil
	}
	t, err = template.ParseGlob("templates/*")
	return t, err
}
Example #13
0
//reload templates on modify
func listenForChanges() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	done := make(chan bool)

	// Process events
	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				log.Println("event:", ev)
				//recompile templates
				templates = template.Must(template.ParseGlob("templates/*.html"))
			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}()

	err = watcher.Watch("templates/")
	if err != nil {
		log.Fatal(err)
	}

	<-done

	watcher.Close()
}
Example #14
0
func helperMustLoadTemplates() *template.Template {
	t, err := template.ParseGlob(config.resourceDir + "/views/posts/*.html")
	if err != nil {
		panic(err.Error())
	}
	return t
}
Example #15
0
func initTemplate() *template.Template {
	t, parseErr := template.ParseGlob("template/*.tmpl")
	if parseErr != nil {
		log.Panicln("NisePostGo: ", parseErr)
	}
	return t
}
Example #16
0
// Run finalizes all options and calls the ListenAndServe function to serve
// requests
func (a *App) Run() {
	fmt.Println("GoingUp App Starting")

	r := mux.NewRouter()

	fs := http.FileServer(http.Dir(a.Options.StaticAssetsDir))
	r.PathPrefix(a.Options.StaticAssetsURL).Handler(http.StripPrefix(a.Options.StaticAssetsURL, fs))

	fmt.Println("Parsing Templates")
	a.Templates = template.Must(template.ParseGlob(a.Options.TemplateDir + "/*"))

	fmt.Println("Parsing Content")
	a.Content = parseContentGlob(a.Options.ContentDir + "/*.md")

	for _, page := range a.Pages {
		content := ""
		if page.ContentName != "" {
			if val, exists := a.Content[page.ContentName]; exists {
				content = val
			}
		}
		page.Content = template.HTML(content)
		r.HandleFunc(page.URL, makePageHandler(a, page))
	}

	strPort := strconv.Itoa(a.Options.Port)
	fmt.Printf("Listening on %s\n", strPort)
	http.ListenAndServe(":"+strPort, newLogHandler(r))
}
Example #17
0
func (a *App) Parse(filepath string) {
	var (
		hashkey  []byte
		blockkey []byte
	)
	file, err := ioutil.ReadFile(filepath)
	if err != nil {
		log.Fatal("Could not parse config.json: ", err)
	}
	if err := json.Unmarshal(file, a); err != nil {
		log.Fatal("Error parsing config.json: ", err)
	}
	if a.Hashkey == "" {
		hashkey = securecookie.GenerateRandomKey(16)
	} else {
		hashkey = []byte(a.Hashkey)
	}
	if a.Blockkey == "" {
		blockkey = securecookie.GenerateRandomKey(16)
	} else {
		blockkey = []byte(a.Blockkey)
	}
	a.Scook = securecookie.New(hashkey, blockkey)
	a.Templates = template.Must(template.ParseGlob("./static/views/*"))
}
Example #18
0
// NewHTML create a HTMLMarshaller with path to templates.
func NewHTML(path string) (Marshaller, error) {
	t, err := template.ParseGlob(path + "/*")
	if err != nil {
		return nil, err
	}
	return &HTMLMarshaller{t}, err
}
Example #19
0
func NewTaskServer(s store.Store, serverUrl, templatesPath, geoipDatabase string) *measurementsServerState {
	queries := make(chan *store.Query)
	go s.WriteQueries(queries)

	measurementIds := generateMeasurementIds()

	go s.ScheduleTaskFunctions()

	taskRequests := make(chan *store.TaskRequest)
	go s.Tasks(taskRequests)

	countResultsRequests := make(chan store.CountResultsRequest)
	go s.CountResultsForReferrer(countResultsRequests)

	geolocator, err := geoip.Open(geoipDatabase)
	if err != nil {
		log.Fatalf("error opening geoip database: %v", err)
	}

	return &measurementsServerState{
		Store:                s,
		Templates:            template.Must(template.ParseGlob(filepath.Join(templatesPath, "[a-zA-Z]*"))),
		Queries:              queries,
		MeasurementIds:       measurementIds,
		TaskRequests:         taskRequests,
		CountResultsRequests: countResultsRequests,
		ServerUrl:            serverUrl,
		Geolocator:           geolocator,
	}
}
Example #20
0
func actionCategoryList(w http.ResponseWriter, req *http.Request) {

	Id := req.URL.Query().Get("id")
	fmt.Println(Id)

	// // param := req.Vars()
	// catId, ok := param["id"]
	// if ok == nil {
	// 	catId = 0
	// }

	var templActionHome *template.Template = template.Must(
		template.ParseGlob("templates/home/*.html"))

	lay := getLayoutTemplates()
	wr := &HtmlContainer{}

	// templActionHome.Funcs(template.FuncMap{"len": Len})
	data := HtmlAssigner{
		"List": getEntryList("", 10),
		"Test": "Test",
	}

	err := templActionHome.Execute(wr, data)
	if err != nil {
		fmt.Errorf("%v", err)
	}

	lay.New("title").Parse("Najnowsze wpisy - " + config.GetStringDef("page", "title", ""))

	err = lay.Execute(w, wr.getHtml())
	if err != nil {
		fmt.Errorf("%v", err)
	}
}
Example #21
0
func main() {
	tpl, _ = template.ParseGlob("templates/html/*.html")
	http.HandleFunc("/", home)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public/"))))
	http.ListenAndServe(":8080", nil)
}
Example #22
0
func actionCategories(w http.ResponseWriter, req *http.Request) {
	var templActionCategories *template.Template = template.Must(
		template.ParseGlob("templates/categories/*.html"))

	wr := &HtmlContainer{}

	// templActionHome.Funcs(template.FuncMap{"len": Len})
	data := HtmlAssigner{
		"List": category.GetTagCloud(),
		"Test": "Test",
	}

	err := templActionCategories.Execute(wr, data)
	if err != nil {
		fmt.Errorf("%v", err)
	}

	lay := getLayoutTemplates()
	lay.New("title").Parse("Lista Kategorii - " + config.GetStringDef("page", "title", ""))

	err = lay.Execute(w, wr.getHtml())
	if err != nil {
		fmt.Errorf("%v", err)
	}
}
Example #23
0
func init() {
	http.HandleFunc("/", handler)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css/"))))
	http.Handle("/img/", http.StripPrefix("/img", http.FileServer(http.Dir("img/"))))
	tpl = template.Must(template.ParseGlob("*.html"))
}
Example #24
0
func init() {
	var err error
	myTemplates, err = template.ParseGlob("*.gohtml")
	if err != nil {
		log.Println(err)
	}
}
Example #25
0
func main() {
	cf := flag.String("config", "freegeoip.conf", "set config file")
	flag.Parse()
	if buf, err := ioutil.ReadFile(*cf); err != nil {
		log.Fatal(err)
	} else {
		conf = &Settings{}
		if err := xml.Unmarshal(buf, conf); err != nil {
			log.Fatal(err)
		}
	}
	templates = template.Must(template.ParseGlob(fmt.Sprintf("%s/template/*.html", conf.DocumentRoot)))
	http.Handle("/", http.FileServer(http.Dir(conf.DocumentRoot)))
	h := GeoipHandler()
	http.HandleFunc("/csv/", h)
	http.HandleFunc("/xml/", h)
	http.HandleFunc("/json/", h)
	http.HandleFunc("/map/", h)
	server := http.Server{
		Addr: conf.Addr,
		Handler: httpxtra.Handler{
			Logger:   logger,
			XHeaders: conf.XHeaders,
		},
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 15 * time.Second,
	}
	log.Printf("FreeGeoIP server starting on %s (xheaders=%t)",
		conf.Addr, conf.XHeaders)
	if e := httpxtra.ListenAndServe(server); e != nil {
		log.Println(e.Error())
	}
}
Example #26
0
func init() {
	// /Users/henrilepic/gocode/src/github.com/konginteractive/cme/
	templatesHtml = htmlTempl.Must(htmlTempl.ParseGlob("./app/vues/*"))
	templatesText = textTempl.Must(textTempl.ParseGlob("./app/vues/*"))
	// permet d'avoir quelques variables
	//fmt.Println("YS : " + YS + " / MS : " + MS)
}
Example #27
0
func httpServer(listener net.Listener) {
	var err error
	templates, err = template.ParseGlob(fmt.Sprintf("%s/*.html", *templateDir))
	if err != nil {
		log.Printf("ERROR: %s", err.Error())
	}

	log.Printf("HTTP: listening on %s", listener.Addr().String())

	handler := http.NewServeMux()
	handler.HandleFunc("/ping", pingHandler)
	handler.HandleFunc("/", indexHandler)
	handler.HandleFunc("/nodes", nodesHandler)
	handler.HandleFunc("/topic/", topicHandler)
	handler.HandleFunc("/delete_topic", deleteTopicHandler)
	handler.HandleFunc("/delete_channel", deleteChannelHandler)
	handler.HandleFunc("/empty_channel", emptyChannelHandler)

	server := &http.Server{
		Handler: handler,
	}
	err = server.Serve(listener)
	// theres no direct way to detect this error because it is not exposed
	if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
		log.Printf("ERROR: http.Serve() - %s", err.Error())
	}

	log.Printf("HTTP: closing %s", listener.Addr().String())
}
Example #28
0
func init() {
	//html files, and strips prefixes for img and css
	tpl, _ = template.ParseGlob("*.html")
	http.HandleFunc("/", main)
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css"))))
	http.Handle("/img/", http.StripPrefix("/img", http.FileServer(http.Dir("img"))))
}
Example #29
0
/* group/status/{groupUUID}
   Respond with the group name, current queue, who is up next in that queue, and if this week has a host yet.
   I'm not sure what this app is going to be yet, api with spa? or server & client code
*/
func DisplayGroupStatus(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	pathVars := mux.Vars(r)

	uuid := pathVars["uuid"]
	ctx.Infof("UUID: %s", uuid)

	if isValidUUID((uuid)) {
		group, err := GetGroupByUUID(ctx, uuid)
		ctx.Infof("group: %v", group)
		if err != nil {
			panic(err)
		}

		status := convertToStatus(group)
		w.Header().Set("Content-Type", "text/html; charset=utf-8")

		var tpl = template.Must(template.ParseGlob("templates/*.html"))
		if err := tpl.ExecuteTemplate(w, "status.html", status); err != nil {
			ctx.Infof("%v", err)
		}

	} else {
		w.Write([]byte("Invalid group"))
	}
}
Example #30
0
func loadTemplates() {
	if Templates == nil {
		t, _ := template.ParseGlob(
			filepath.Join(config.Get("email"), "*.*"))
		Templates = t
	}
}