func main() { c, err := config.ReadDefault("wiki.ini") panicIni(err) wikiName, err = c.String("wiki", "name") panicIni(err) servAddr, err := c.String("wiki", "serv_addr") panicIni(err) inDevMode, err = c.Bool("wiki", "dev_mode") panicIni(err) log.Printf("Read wiki.ini") views = template.Must(template.ParseGlob("views/[a-z]*.html")) log.Printf("Parsed page templates\n") http.HandleFunc("/", rootHandler) http.HandleFunc("/delete/", deleteHandler) http.HandleFunc("/restore/", restoreHandler) http.HandleFunc("/edit/", editHandler) http.HandleFunc("/preview", previewHandler) http.HandleFunc("/save/", saveHandler) http.HandleFunc("/pages", pagesHandler) http.HandleFunc("/deleted", deletedHandler) http.HandleFunc("/versions/", versionsHandler) http.HandleFunc("/search", searchHandler) http.Handle("/pub/", http.StripPrefix("/pub/", http.FileServer(http.Dir("pub")))) http.HandleFunc("/favicon.ico", faviconHandler) log.Printf("Serving wiki pages from %s...\n", servAddr) log.Fatal(http.ListenAndServe(servAddr, nil)) }
func startup() { loadConfig() log.Printf("Lanyon listening on http://localhost:%d", config.PortNum) // add trailing slashes to config directories if !strings.HasSuffix(config.PublicDir, "/") { config.PublicDir = config.PublicDir + "/" } // verify public directory exists if _, err := os.Stat(config.PublicDir); err != nil { log.Fatalln("Public directory does not exist") } // add trailing slashes to config directories if !strings.HasSuffix(config.TemplateDir, "/") { config.TemplateDir = config.TemplateDir + "/" } // verify template directory exists if _, err := os.Stat(config.TemplateDir); err != nil { log.Fatalln("Template directory does not exist") } var err error ts, err = template.ParseGlob(config.TemplateDir + "*.html") if err != nil { log.Fatalln("Error Parsing Templates: ", err) } }
func main() { tpl, err := template.ParseGlob("templates/*.gmao") if err != nil { log.Fatalln(err) } err = tpl.Execute(os.Stdout, nil) if err != nil { log.Fatalln(err) } err = tpl.ExecuteTemplate(os.Stdout, "vespa.gmao", nil) if err != nil { log.Fatalln(err) } err = tpl.ExecuteTemplate(os.Stdout, "two.gmao", nil) if err != nil { log.Fatalln(err) } err = tpl.ExecuteTemplate(os.Stdout, "one.gmao", nil) if err != nil { log.Fatalln(err) } }
func FindAndExecuteTemplate(currentDir string, templateName string, concept Concept) error { templateDir, err := utils.FindTemplateDir() if err != nil { return err } endpointDir, err := MakeEndpointDir(currentDir, concept) if err != nil { return err } //TODO assume that js is the only implementation language for now templatesGlob := fmt.Sprintf("%v/js/endpoint/*.js", templateDir) t, err := template.ParseGlob(templatesGlob) if err != nil { return err } outputFileName := fmt.Sprintf("%v/%v", endpointDir, templateName) outputFile, err := os.Create(outputFileName) if err != nil { return err } return t.ExecuteTemplate(outputFile, templateName, concept) }
func NewTheme(tpath string) *Theme { var err error var pattern string var pages []string var base *template.Template var tmap = map[string]*template.Template{} pattern = path.Join(tpath, "*.html") base = template.Must(template.ParseGlob(pattern)) pattern = path.Join(tpath, "pages", "*.html") if pages, err = filepath.Glob(pattern); err != nil { panic(err) } for _, tpath := range pages { var ts *template.Template if ts, err = base.Clone(); err != nil { panic(err) } if _, err = ts.ParseFiles(tpath); err != nil { panic(err) } tmap[path.Base(tpath)] = ts } return &Theme{ Path: tpath, Templates: tmap, } }
func Start(conn *CGRConnector, user, pass string) { connector = conn username = user password = pass templates = template.Must(template.ParseGlob("templates/*.tmpl")) rpc.Register(conn) goji.Get(LOGIN_PATH, loginGet) goji.Post(LOGIN_PATH, loginPost) goji.Get("/app/*", http.FileServer(http.Dir("./static"))) auth := web.New() goji.Handle("/*", auth) auth.Use(SessionAuth) auth.Handle("/ws", websocket.Handler(func(ws *websocket.Conn) { jsonrpc.ServeConn(ws) })) auth.Post("/import/", importPost) auth.Post("/exportcdrs/", exportCdrsPost) auth.Post("/exporttpcsv/", exportTpToCsvPost) auth.Get("/accounts/logout", logoutGet) auth.Get("/", http.RedirectHandler("/app/", 301)) }
func ServeServerRoutes(port string, pusher *UDPush.Pusher) { Pusher = pusher var err error T, err = template.ParseGlob("server/templates/*") _ = err r := mux.NewRouter() r.StrictSlash(true) // public r.HandleFunc("/", IndexHandler) r.HandleFunc("/login/", LoginHandler).Methods("GET") r.HandleFunc("/sign-up/", SignUpHandler).Methods("POST") r.HandleFunc("/file-data/{email}", FilesHandler).Methods("POST") r.HandleFunc("/download/{id}/{filename}", DownloadHandler).Methods("GET") // require client authentication r.HandleFunc("/file-actions/", sessionValidate(FileActionsHandler)).Methods("POST") r.HandleFunc("/upload/", sessionValidate(UploadHandler)).Methods("POST") r.HandleFunc("/download/", sessionValidate(FileDownloadHandler)).Methods("POST") r.HandleFunc("/clients/", sessionValidate(ClientsFileActionsHandler)).Methods("POST") // static files? (css, js, etc...) // r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/"))) http.Handle("/", r) fmt.Println("Serving api on port :" + port) http.ListenAndServe(":"+port, nil) }
func New(addr string, auth smtp.Auth, templateDir string) (Mailer, error) { templates, err := template.ParseGlob(filepath.Join(templateDir, "*.tmpl")) if err != nil { return nil, err } return &defaultMailer{addr, auth, templates}, nil }
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 main() { res, _ := filepath.Glob("templates\\temp\\*.html") log.Printf("%+v", res) var templates = template.Must(template.ParseGlob("templates\\temp\\*.html")) err := templates.ExecuteTemplate( os.Stdout, "indexPage", View{Content: "foo"}, ) if err != nil { log.Printf("err: %v", err) return } m := martini.Classic() // render html templates from templates directory m.Use(render.Renderer(render.Options{ Directory: "templates/temp", Extensions: []string{".html"}, })) m.Get("/", func(r render.Render) { r.HTML(200, "head", View{Content: "tututrutu"}, render.HTMLOptions{Layout: "indexPage"}) }) m.Run() }
// ディレクトリにあるテンプレート郡をロードするデモです。 func main() { dir := createTestDir([]templateFile{ // T0.tmpl はT1をコールします。 {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`}, // T1.tmpl T2をコールするテンプレートを"T1"として定義しています。 {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`}, // T2.tmpl は"T2"としてテンプレートを定義しています。 {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`}, }) // main関数終了後、作成したディレクトリを削除します。 defer os.RemoveAll(dir) // dirにあるすべてのテンプレートファイルを検索するようにパターンを作成しています。 pattern := filepath.Join(dir, "*.tmpl") // ここから本題です。 // T0.tmpl は初めにマッチする名前ですので、始めのテンプレート(ParseGlobの戻り値の値)になります。 tmpl := template.Must(template.ParseGlob(pattern)) log.Println(tmpl.Name()) err := tmpl.Execute(os.Stdout, nil) if err != nil { log.Fatalf("template execution: %s", err) } // Output: // T0 invokes T1: (T1 invokes T2: (This is T2)) }
// 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) } }
func TestSendNags(t *testing.T) { stats, _ := statsd.NewNoopClient(nil) mc := mocks.Mailer{} rs := newFakeRegStore() fc := newFakeClock(t) m := mailer{ stats: stats, mailer: &mc, emailTemplate: tmpl, subject: testEmailSubject, rs: rs, clk: fc, } cert := &x509.Certificate{ Subject: pkix.Name{ CommonName: "happy", }, NotAfter: fc.Now().AddDate(0, 0, 2), DNSNames: []string{"example.com"}, } err := m.sendNags([]*core.AcmeURL{emailA}, []*x509.Certificate{cert}) test.AssertNotError(t, err, "Failed to send warning messages") test.AssertEquals(t, len(mc.Messages), 1) test.AssertEquals(t, mocks.MailerMessage{ To: emailARaw, Subject: testEmailSubject, Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.RFC822Z)), }, mc.Messages[0]) mc.Clear() err = m.sendNags([]*core.AcmeURL{emailA, emailB}, []*x509.Certificate{cert}) test.AssertNotError(t, err, "Failed to send warning messages") test.AssertEquals(t, len(mc.Messages), 2) test.AssertEquals(t, mocks.MailerMessage{ To: emailARaw, Subject: testEmailSubject, Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.RFC822Z)), }, mc.Messages[0]) test.AssertEquals(t, mocks.MailerMessage{ To: emailBRaw, Subject: testEmailSubject, Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.RFC822Z)), }, mc.Messages[1]) mc.Clear() err = m.sendNags([]*core.AcmeURL{}, []*x509.Certificate{cert}) test.AssertNotError(t, err, "Not an error to pass no email contacts") test.AssertEquals(t, len(mc.Messages), 0) templates, err := template.ParseGlob("../../data/*.template") test.AssertNotError(t, err, "Failed to parse templates") for _, template := range templates.Templates() { m.emailTemplate = template err = m.sendNags(nil, []*x509.Certificate{cert}) test.AssertNotError(t, err, "failed to send nag") } }
func main() { var err error cwd, _ := os.Getwd() client := flag.String("client", path.Join(cwd, "client"), "Full path to client directory.") addr := flag.String("listen", "127.0.0.1:8088", "Listen address.") templates, err = template.ParseGlob(path.Join(*client, "*.html")) if err != nil { log.Fatal("Failed to load templates: ", err) } flag.Parse() go h.run() http.HandleFunc("/", serveClient) http.HandleFunc("/realtimetraffic", serveWs) http.Handle("/css/", http.FileServer(http.Dir(*client))) http.Handle("/scripts/", http.FileServer(http.Dir(*client))) http.Handle("/img/", http.FileServer(http.Dir(*client))) http.Handle("/favicon.ico", http.FileServer(http.Dir(*client))) err = http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
func init() { var err error Templates, err = template.ParseGlob("templates/*/*.html") if err != nil { panic(err) } }
// Here we demonstrate loading a set of templates from a directory. func ExampleTemplate_glob() { // Here we create a temporary directory and populate it with our sample // template definition files; usually the template files would already // exist in some location known to the program. dir := createTestDir([]templateFile{ // T0.tmpl is a plain template file that just invokes T1. {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`}, // T1.tmpl defines a template, T1 that invokes T2. {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`}, // T2.tmpl defines a template T2. {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`}, }) // Clean up after the test; another quirk of running as an example. defer os.RemoveAll(dir) // pattern is the glob pattern used to find all the template files. pattern := filepath.Join(dir, "*.tmpl") // Here starts the example proper. // T0.tmpl is the first name matched, so it becomes the starting template, // the value returned by ParseGlob. tmpl := template.Must(template.ParseGlob(pattern)) err := tmpl.Execute(os.Stdout, nil) if err != nil { log.Fatalf("template execution: %s", err) } // Output: // T0 invokes T1: (T1 invokes T2: (This is T2)) }
func (r Renderer) RenderAll(site *SiteContext, posts []*Post) error { templates := template.Must( template.ParseGlob(path.Join(r.TemplatePath, "*.html"))) // ensure the output directory exists err := os.MkdirAll(path.Join(r.OutputPath), 0755) if err != nil { return err } // copy assets cpDir(path.Join(r.TemplatePath, "assets"), path.Join(r.OutputPath, "assets")) // make the index page index, err := os.Create(path.Join(r.OutputPath, "index.html")) if err != nil { log.Panicf(err.Error()) } err = templates.ExecuteTemplate(index, "index.html", &IndexContext{site, posts, "Home", ""}) // gratuitous use of goroutines // use a WaitGroup to ensure all goroutines get access to STDOUT var wg sync.WaitGroup for _, post := range posts { wg.Add(1) go func(site *SiteContext, post *Post) { defer wg.Done() pc := &PostContext{site, post, "../"} r.RenderPost(pc, templates) }(site, post) } wg.Wait() return nil }
func AddTemplGlob(pattern string) { var err error templates, err = template.ParseGlob(pattern) if err != nil { log.Println("parse templates failed,", err) } //templates.ParseFiles("/temps/cover.html") }
func loadTemplates() { //Load templates tmpl := template.Must(template.ParseGlob("views/*.html")) for _, t := range tmpl.Templates() { // log.Printf("Template imported: %s", t.Name()) Templates[t.Name()] = t } }
func aatmplMain() error { templates := filepath.Join("templates", "*.tmpl") tmpl, err := template.ParseGlob(templates) if err != nil { return err } // generate cmd/aa2txt/aa2txt.go fp, err := os.Create(filepath.Join("cmd", "aa2txt", "aa2txt.go")) if err != nil { return err } defer fp.Close() err = tmpl.ExecuteTemplate(fp, "aa2txt.tmpl", map[string]string{ "MainFunc": "toTxt(asciiArt string)", }) if err != nil { return err } // generate example.go example := filepath.Join("util", "cmd", "aaexample", "aaexample.go") fp, err = os.Create(example) if err != nil { return err } defer fp.Close() err = tmpl.ExecuteTemplate(fp, "exampleprog.tmpl", map[string]string{ "MainFunc": "main()", }) if err != nil { return err } // execute example.go and capture output for README.md output, err := runExample(example) if err != nil { return err } // generate README.md fp, err = os.Create("README.md") if err != nil { return err } defer fp.Close() err = tmpl.ExecuteTemplate(fp, "readme.tmpl", map[string]string{ "MainFunc": "main()", "Output": output, "Usage": getUsage(), }) if err != nil { return err } return nil }
func render(w http.ResponseWriter, templateName string, data interface{}) { if inDevMode { views = template.Must(template.ParseGlob("views/[a-z]*.html")) } err := views.ExecuteTemplate(w, templateName, data) if err != nil { serverError(w, err) } }
func init() { t, err := template.ParseGlob("templates/*") t.Parse( fmt.Sprintf(`{{define "hash"}}%d{{end}}`, time.Now().Unix()), ) if err != nil { log.Fatal(err) } T = template.Must(t, err) }
func NewRouter(routes []Route, logger *Logger) *Router { templates, _ := template.ParseGlob("./templates/*.html") router := Router{routes: make(map[string]*Route), logger: logger, templates: templates} for _, route := range routes { router.AddRoute(route.Method, route.Path, &route) } return &router }
// buildToc generates the table of contents for the epub file. func (w *EpubArchive) buildToc(opf Opf) Chapter { tmpl := template.Must(template.ParseGlob(templateGlob)) buf := new(bytes.Buffer) err := tmpl.ExecuteTemplate(buf, "toc.xhtml.tpl", opf.RootFiles[0].Manifest) if err != nil { log.Fatalf("template execution: %s", err) } toc := Chapter{FileName: "chapters/toc.xhtml", Contents: string(buf.Bytes())} return toc }
// Renders current site to html func Render_Site() error { var err error filepath.Walk(config.SourceDir, Walker) var pages PagesSlice for _, dir := range site.Directories { readglob := dir + "/*.md" var dirfiles, _ = filepath.Glob(readglob) // loop through files in directory for _, file := range dirfiles { //fmt.Println(" File:", file) outfile := filepath.Base(file) outfile = strings.Replace(outfile, ".md", ".html", 1) // read & parse file for parameters page := readParseFile(file) page.OutFile = dir + "/" + outfile // create array of parsed pages pages = append(pages, page) } } //fmt.Printf("%v\n", pages) layoutsglob := config.TemplateDir + "/*.html" _, err = template.ParseGlob(layoutsglob) if err != nil { PrintErr("Error Parsing Templates: ", err) os.Exit(1) } for _, page := range pages { html := applyTemplates(page) fmt.Println(page.Url) err = WritePage(page, html) if err != nil { PrintErr("Cant generate site", err) os.Exit(1) } } // Generate index listings... for _, dir := range site.Directories { html, page, _ := getDirectoryListing(dir) err = WritePage(page, html) if err != nil { PrintErr("Error writing index files", err) os.Exit(1) } WriteJson(page, dir) } return nil }
func main() { // Load the templates. tmpl, err := template.ParseGlob("cuckoo.tmpl") if err != nil { log.Fatal(err) } tmplTest, err := template.ParseGlob("cuckoo_test.tmpl") if err != nil { log.Fatal(err) } tmplBench, err := template.ParseGlob("bench_test.tmpl") if err != nil { log.Fatal(err) } // Generate Cuckoo filter types. for _, data := range []cData{ {Name: "S", NumBits: 8, NumBitsFingerprint: 4, Desc: "1 byte per item", ErrRate: 11, MaxInserts: 2}, {Name: "M", NumBits: 16, NumBitsFingerprint: 8, Desc: "2 bytes per item", ErrRate: 1, MaxInserts: 2}, {Name: "L", NumBits: 32, NumBitsFingerprint: 16, Desc: "4 bytes per item", ErrRate: 0.005, MaxInserts: 2}, // similar error rate as bucket 32 / fingerprint 16 with twice the memory footprint // {Name: "L", NumBits: 64, NumBitsFingerprint: 16, Desc: "8 bytes per item", ErrRate: 0.005, MaxInserts: 4}, } { log.Printf("Generating %s\n", data.Name) // Compute the uint size to hold a fingerprint data.NumBitsFingerprintUint = power2(data.NumBitsFingerprint) if data.NumBitsFingerprintUint < 8 { data.NumBitsFingerprintUint = 8 } genFile(fmt.Sprintf("cuckoo%s.go", data.Name), tmpl, &data) genFile(fmt.Sprintf("cuckoo%s_test.go", data.Name), tmplTest, &data) genFile(fmt.Sprintf("bench%s_test.go", data.Name), tmplBench, &data) } log.Println("Running go fmt") cmd := exec.Command("go", "fmt") cmd.Dir = "." cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
func build() { var err error t, err = template.ParseGlob("templates/*.t") if err != nil { log.Fatal(err) return } parseCategories() filepath.Walk("posts", func(path string, info os.FileInfo, err error) error { if !info.IsDir() && filepath.Ext(path) == ".md" { p, err := parsePost(path) if err != nil { log.Error(err) return nil } var b bytes.Buffer if p.HTML != "" { b = *bytes.NewBufferString(p.Content) } else { err = t.ExecuteTemplate(&b, "post.t", p) if err != nil { log.Error(err) return nil } } pages["/"+p.Name] = b addPostToCategory(p) addPostToFeed(p) } return nil }) log.Info("create home page") var b bytes.Buffer err = t.ExecuteTemplate(&b, "index.t", categories) log.FatalOnError(err) pages["/"] = b log.Info("create feeds") feed := feed() atom, err := feed.ToAtom() log.FatalOnError(err) pages["/feed"] = *bytes.NewBufferString(atom) rss, err := feed.ToRss() log.FatalOnError(err) pages["/rss"] = *bytes.NewBufferString(rss) }
// NewTemplatizedEmailerFromGlobs creates a new TemplatizedEmailer, parsing the templates found in the given filepattern globs. func NewTemplatizedEmailerFromGlobs(textGlob, htmlGlob string, emailer Emailer) (*TemplatizedEmailer, error) { textTemplates, err := template.ParseGlob(textGlob) if err != nil { return nil, err } htmlTemplates, err := htmltemplate.ParseGlob(htmlGlob) if err != nil { return nil, err } return NewTemplatizedEmailerFromTemplates(textTemplates, htmlTemplates, emailer), nil }
func main() { var pattern string flag.StringVar(&pattern, "p", "templates/*.html", "template pattern like template/*.html") template, err := template.ParseGlob(pattern) if err != nil { fmt.Fprintln(os.Stderr, err.Error()) } var mainTemplate string flag.StringVar(&mainTemplate, "t", "index", "main template like index") template.ExecuteTemplate(os.Stdout, mainTemplate, nil) }
func main() { router := mux.NewRouter() htmlTemplates = template.Must(template.ParseGlob("templates/*")) font = readFont() router.HandleFunc("/", homePage) router.HandleFunc("/generate", handleForm).Methods("POST") router.PathPrefix("/assets").Handler(staticHandler()) http.Handle("/", router) log.Fatal(http.ListenAndServe(":8001", nil)) }