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) } }
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) } }
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) } }
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()) } }
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) } }
func ParseGlob(pattern string) (Template, error) { if Debug { return (&reloadTemplate{}).ParseGlob(pattern) } t, err := htmlTmpl.ParseGlob(pattern) return &instantTemplate{t}, err }
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) } } }
// 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) } }
// set everything up. func init() { tpl = template.Must(template.ParseGlob("*.html")) resourceHandler("css") resourceHandler("img") resourceHandler("photos") http.HandleFunc("/", mainPage) }
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) } }
func loadTemplates() (templates *template.Template, err error) { if !*devMode && t != nil { return t, nil } t, err = template.ParseGlob("templates/*") return t, err }
//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() }
func helperMustLoadTemplates() *template.Template { t, err := template.ParseGlob(config.resourceDir + "/views/posts/*.html") if err != nil { panic(err.Error()) } return t }
func initTemplate() *template.Template { t, parseErr := template.ParseGlob("template/*.tmpl") if parseErr != nil { log.Panicln("NisePostGo: ", parseErr) } return t }
// 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)) }
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/*")) }
// 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 }
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, } }
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) } }
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) }
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) } }
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")) }
func init() { var err error myTemplates, err = template.ParseGlob("*.gohtml") if err != nil { log.Println(err) } }
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()) } }
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) }
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()) }
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")))) }
/* 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")) } }
func loadTemplates() { if Templates == nil { t, _ := template.ParseGlob( filepath.Join(config.Get("email"), "*.*")) Templates = t } }