func init() { ALL_METHODS = []string{GET, HEAD, POST, CONNECT, DELETE, OPTIONS, PUT, TRACE} defaultMimeTypes = make(map[string]string) defaultMimeTypes[".htm"] = MIME_TYPE_HTML defaultMimeTypes[".html"] = MIME_TYPE_HTML defaultMimeTypes[".xhtml"] = MIME_TYPE_XHTML_XML defaultMimeTypes[".xml"] = MIME_TYPE_XML defaultMimeTypes[".css"] = MIME_TYPE_CSS defaultMimeTypes[".js"] = MIME_TYPE_JAVASCRIPT defaultMimeTypes[".json"] = MIME_TYPE_JSON defaultMimeTypes[".jpg"] = MIME_TYPE_JPEG defaultMimeTypes[".jpeg"] = MIME_TYPE_JPEG defaultMimeTypes[".gif"] = MIME_TYPE_GIF defaultMimeTypes[".png"] = MIME_TYPE_PNG defaultMimeTypes[".ico"] = MIME_TYPE_ICO defaultMimeTypes[".swf"] = MIME_TYPE_SWF defaultMimeTypes[".zip"] = MIME_TYPE_ZIP defaultMimeTypes[".bz2"] = MIME_TYPE_BZIP2 defaultMimeTypes[".gz"] = MIME_TYPE_GZ defaultMimeTypes[".tar"] = MIME_TYPE_TAR defaultMimeTypes[".tgz"] = MIME_TYPE_GZ defaultMimeTypes[".htc"] = MIME_TYPE_COMPONENT defaultMimeTypes[".manifest"] = MIME_TYPE_CACHE_MANIFEST defaultMimeTypes[".svg"] = MIME_TYPE_SVG defaultMimeTypes[".txt"] = MIME_TYPE_TEXT_PLAIN defaultMimeTypes[".text"] = MIME_TYPE_TEXT_PLAIN defaultMimeTypes[".csv"] = MIME_TYPE_CSV HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE, _ = template.New("directory_listing_success").Parse(HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE_STRING) HTML_DIRECTORY_LISTING_ERROR_TEMPLATE, _ = template.New("directory_listing_error").Parse(HTML_DIRECTORY_LISTING_ERROR_TEMPLATE_STRING) }
func init() { rand.Seed(time.Nanoseconds()) // TODO: This should end up in a configuration file schema = &grapher.Schema{FileSchemas: map[string]*grapher.FileSchema{ "application/x-lightwave-book": &grapher.FileSchema{EntitySchemas: map[string]*grapher.EntitySchema{ "application/x-lightwave-entity-chapter": &grapher.EntitySchema{FieldSchemas: map[string]*grapher.FieldSchema{ "after": &grapher.FieldSchema{Type: grapher.TypeEntityBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone}, "title": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest}, "color": &grapher.FieldSchema{Type: grapher.TypeInt64, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest}}}, "application/x-lightwave-entity-page": &grapher.EntitySchema{FieldSchemas: map[string]*grapher.FieldSchema{ "after": &grapher.FieldSchema{Type: grapher.TypeEntityBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone}, "title": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest}, "chapter": &grapher.FieldSchema{Type: grapher.TypeEntityBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone}, "page": &grapher.FieldSchema{Type: grapher.TypePermaBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone}}}}}, "application/x-lightwave-page": &grapher.FileSchema{EntitySchemas: map[string]*grapher.EntitySchema{ "application/x-lightwave-entity-content": &grapher.EntitySchema{FieldSchemas: map[string]*grapher.FieldSchema{ "layout": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone}, "style": &grapher.FieldSchema{Type: grapher.TypeMap, ElementType: grapher.TypeNone, Transformation: grapher.TransformationMerge}, "cssclass": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest}, "text": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationMerge}}}}}}} frontPageTmpl = template.New(nil) frontPageTmpl.SetDelims("{{", "}}") if err := frontPageTmpl.ParseFile("notebook.html"); err != nil { frontPageTmplErr = fmt.Errorf("tmpl.ParseFile failed: %v", err) return } appLoginPageTmpl = template.New(nil) appLoginPageTmpl.SetDelims("{{", "}}") if err := appLoginPageTmpl.ParseFile("applogin.html"); err != nil { appLoginPageTmplErr = fmt.Errorf("tmpl.ParseFile failed: %v", err) return } http.HandleFunc("/", handleFrontPage) http.HandleFunc("/private/submit", handleSubmit) http.HandleFunc("/private/open", handleOpen) http.HandleFunc("/private/close", handleClose) http.HandleFunc("/private/listpermas", handleListPermas) http.HandleFunc("/private/listinbox", handleListInbox) http.HandleFunc("/private/listunread", handleListUnread) http.HandleFunc("/private/invitebymail", handleInviteByMail) http.HandleFunc("/private/inboxitem", handleInboxItem) http.HandleFunc("/private/markasread", handleMarkAsRead) http.HandleFunc("/private/markasarchived", handleMarkAsArchived) http.HandleFunc("/signup", handleSignup) http.HandleFunc("/logout", handleLogout) http.HandleFunc("/login", handleLogin) http.HandleFunc("/applogin", handleAppLogin) http.HandleFunc("/internal/notify", handleDelayedNotify) http.HandleFunc("/_ah/channel/connected/", handleConnect) http.HandleFunc("/_ah/channel/disconnected/", handleDisconnect) // http.HandleFunc("/import", handleImport) }
func init() { BrowseT = template.New(nil) BrowseT.SetDelims("{{", "}}") BrowseT.ParseFile(BrowseTemplatePath) BrowseChooseT = template.New(nil) BrowseChooseT.SetDelims("{{", "}}") BrowseChooseT.ParseFile(BrowseChooseTemplatePath) }
func main() { t := make(map[string][]Template) v := visitor{t} filepath.Walk(HtmlDir, &v, nil) indexBinder := IndexBinder{make([]Package, 0), make([]Template, 0)} for packagePath, templates := range v.Templates { filename := packagePath[strings.LastIndex(packagePath, "/")+1:] binder := Binder{filename, templates} temp := template.New("") p, err := temp.Parse(getTemplate()) if err != nil { fmt.Println("Error!", err.String()) return } htmlDirWithoutSlash := HtmlDir if strings.HasSuffix(htmlDirWithoutSlash, "/") { htmlDirWithoutSlash = htmlDirWithoutSlash[0 : len(htmlDirWithoutSlash)-1] } htmlDirWithoutBaseDir := htmlDirWithoutSlash[0:strings.LastIndex(htmlDirWithoutSlash, "/")] fullFilename := fmt.Sprint(htmlDirWithoutBaseDir, "/", packagePath, "/", filename, ".go") fmt.Println("fullFilename: ", fullFilename) f, _ := os.Create(fullFilename) defer f.Close() p.Execute(f, binder) indexBinder.Packages = append(indexBinder.Packages, Package{PackageName: filename, PackagePath: packagePath, PackagePathUnderscores: strings.Replace(packagePath, "/", "_", -1)}) for _, template := range templates { indexBinder.Templates = append(indexBinder.Templates, template) } } tempIndex := template.New("") tempIndexParsed, err := tempIndex.Parse(getTemplateIndex()) if err != nil { fmt.Println("Error!", err.String()) return } fIndex, _ := os.Create(IndexFile) defer fIndex.Close() tempIndexParsed.Execute(fIndex, indexBinder) fmt.Println("Done!!") }
func generateRouter() { //mkdir for the initiator err := os.MkdirAll(*TargetFullPath+"/router/", 0755) if err != nil { fmt.Println("Unable to create directory, ", err.String()) } f, err := os.Create(*TargetFullPath + "/router/" + "router.go") if err != nil { fmt.Println(err.String()) } defer f.Close() var templ *template.Template templ = template.New(nil) templ.SetDelims("<%", "%>") err = templ.Parse(routerTemplate) if err != nil { fmt.Println(err.String()) } err = templ.Execute(f, map[string]interface{}{ "PackageName": *PackageName, "ServiceName": *ServiceName, }) if err != nil { fmt.Println(err.String()) } }
func init() { chatTempl = template.New(nil) chatTempl.SetDelims("«", "»") if err := chatTempl.Parse(chatStr); err != nil { panic("template error: " + err.String()) } }
func parse(name, s string) *template.Template { t, err := template.New(name).Parse(s) if err != nil { panic(fmt.Sprintf("%q: %s", name, err)) } return t }
func ShowErrors(templateString string) Middleware { if templateString == "" { templateString = ` <html> <body> <p> {{.Error|html}} </p> </body> </html> ` } errorTemplate := template.Must(template.New("error").Parse(templateString)) return func(env Env, app App) (status Status, headers Headers, body Body) { defer func() { if err := recover(); err != nil { buffer := bytes.NewBufferString("") errorTemplate.Execute(buffer, struct{ Error string }{fmt.Sprintf("%s", err)}) status = 500 headers = Headers{} body = Body(buffer.String()) } }() return app(env) } }
func init() { homeTempl = template.New("") //homeTempl.SetDelims("<<", ">>") if _, err := homeTempl.Parse(homeStr); err != nil { panic("template error: " + err.String()) } }
func init() { homeTempl = template.New(nil) homeTempl.SetDelims("<<", ">>") if err := homeTempl.ParseFile("index.html"); err != nil { panic("template error: " + err.String()) } }
// articleJSON handles generates the JSON of a specified Article struct. This is // used as part of the admin manager, to be able to preview and edit the articles // with JSON. func articleJSON(w http.ResponseWriter, r *http.Request) { // Sanity check to ensure that at least /some/ sort of ID was given path := strings.Split(r.URL.Path, "/") if len(path) < 4 || path[3] == "" { errorGenerator(w, "No Article ID provided", 404) return } // Fetch Article struct based on ID given c := appengine.NewContext(r) a, err := getArticle(c, path[3]) check(err) // Generate JSON via the template. Can't use the JSON marshaller because we // don't want to represent the ShortBody & Body as JSON-encoded []bytes, but // as JSON-escaped strings. The template function is also provided with a // special function to escape the ShortBody & Body for JSON representation. t := template.New("articleJSON") t.Funcs(template.FuncMap{"json": escapeForJSON}) t, err = t.ParseFile("templates/article.json") check(err) // Execute the template, using the Article struct as a source err = t.Execute(w, a) check(err) }
// articlesIndex is the handler for the site's index page. // It shows up to the last 10 article summaries (all public info except // for the Body) on a single page. func articlesIndex(w http.ResponseWriter, r *http.Request) { // Get the user-entered offset, or default to a zero offset. offsetS := r.FormValue("Page") var offset int if len(offsetS) > 0 { offset64, err := strconv.Btoi64(offsetS, 10) check(err) offset = int(offset64) } else { offset = 0 } // Fetch public data from datastore, up to 10, with offset `offset * 10` c := appengine.NewContext(r) q := datastore.NewQuery("Article").Order("-Date").Filter("Public =", true).Limit(10).Offset(10 * offset) a := make([]Article, 0, 10) _, err := q.GetAll(c, &a) check(err) // Prepares the `indexTemplate.html` template t := template.New("index") t, err = t.ParseFile("templates/indexTemplate.html") check(err) // Executes the template, providing the data gathered from the datastore err = t.Execute(w, a) check(err) }
func init() { homeTempl = template.New(nil) homeTempl.SetDelims("«", "»") if err := homeTempl.Parse(homeStr2); err != nil { panic("template error: " + err.String()) } }
// Add adds a given template string to the template manager. // If any errors occur, err will be non-nil. func (m *Manager) add(s string, id string, mustParse bool) (t *Template, err os.Error) { tt := template.New(m.fmap) tt.SetDelims(m.ldelim, m.rdelim) // Parse the template. if mustParse { err := tt.Parse(s) if err != nil { panic(err) } } else { err := tt.Parse(s) if err != nil { return } } t = &Template{ m: m, cache: tt} // Add template to the manager. m.tStrings[id] = t return }
func TestAutoesc(t *testing.T) { for _, testCase := range testCases { name := testCase.name tmpl := template.New(name) tmpl, err := tmpl.Parse(testCase.input) if err != nil { t.Errorf("%s: failed to parse template: %s", name, err) continue } Escape(tmpl) buffer := new(bytes.Buffer) err = tmpl.Execute(buffer, testData) if err != nil { t.Errorf("%s: template execution failed: %s", name, err) continue } output := testCase.output actual := buffer.String() if output != actual { t.Errorf("%s: escaped output: %q != %q", name, output, actual) } } }
func parseTemplate(filename string) *Template { return &Template{ t: template.Must(template.New(filename). Funcs(template.FuncMap{"item": itemFormatter}). ParseFile(path.Join("template", filename))), mimeType: mime.TypeByExtension(path.Ext(filename))} }
/* * Run the program * * Usage: * ./ls [args] directory_name * * possible args: * -R: go through directories recursively * -n: print with information * -t: sort files by modification time * * if no arguments are getting, print out alphabetically with 1 file * per line */ func main() { var R *bool var n *bool var t *bool R = flag.Bool("R", false, "go through directories recursively") n = flag.Bool("n", false, "print with information") t = flag.Bool("t", false, "sort files by modification time") flag.Parse() args := flag.Args() if len(args) == 0 { args = []string{"./"} } defer func() { if r := recover(); r != nil { fmt.Fprintln(os.Stderr, "Invalid Arguments") } }() temp := template.Must(template.New("ls").Parse("{{.Mode}} {{printf `%3d` .Nlink}} {{.Uid}} {{.Gid}} {{printf `%7d` .Size}} {{.Mtime}} {{.Name}}\n")) for _, arg := range args { if data, error := ls.Ls(arg, *R, *t); error == nil { path := data[0][0].Name if strings.HasSuffix(path, "/") { path = path[0 : len(path)-1] } printFiles(flag.NArg(), data, path, n, temp) } else { fmt.Fprintln(os.Stderr, "File or directory not found") } } }
// escapeTree escapes the named template starting in the given context as // necessary and returns its output context. func (e *escaper) escapeTree(c context, name string, line int) (context, string) { // Mangle the template name with the input context to produce a reliable // identifier. dname := c.mangle(name) e.called[dname] = true if out, ok := e.output[dname]; ok { // Already escaped. return out, dname } t := e.template(name) if t == nil { return context{ state: stateError, err: errorf(ErrNoSuchTemplate, line, "no such template %s", name), }, dname } if dname != name { // Use any template derived during an earlier call to EscapeSet // with different top level templates, or clone if necessary. dt := e.template(dname) if dt == nil { dt = template.New(dname) dt.Tree = &parse.Tree{Name: dname, Root: cloneList(t.Root)} e.derived[dname] = dt } t = dt } return e.computeOutCtx(c, t), dname }
// articleHandler is the handler for /article/* links. // It is passed an ArticleID by the user, which is then fetched from // the datastore and displayed using the articleTemplate.html template func articleHandler(w http.ResponseWriter, r *http.Request) { path := strings.Split(r.URL.Path, "/") // Ensure there's at least 3 elements long, with the third element // not being an empty string if len(path) < 3 || path[2] == "" { errorGenerator(w, "No Article ID provided", 404) return } c := appengine.NewContext(r) a, err := getArticle(c, path[2]) // If there was an error, give special error if the ArticleID was // missing from the datastore, otherwise use normal error path if err != nil { if err == datastore.ErrNoSuchEntity { // Handle invalid IDs in a special manner. errorGenerator(w, "Article not found", 404) return } else { // Some other error must be present, so use default handler check(err) } } // Create the article template t := template.New("article") t, err = t.ParseFile("templates/articleTemplate.html") check(err) // Execute the article template, populated with the Article struct err = t.Execute(w, a) check(err) }
func init() { mainTemplate = template.New(template.FormatterMap{}) mainTemplate.SetDelims("{{", "}}") if err := mainTemplate.Parse(rawTemplate); err != nil { panic("synthesizer: bad template: " + err.String()) } }
func TestEscapeErrorsNotIgnorable(t *testing.T) { var b bytes.Buffer tmpl := template.Must(template.New("dangerous").Parse("<a")) Escape(tmpl) err := tmpl.Execute(&b, nil) expectExecuteFailure(t, &b, err) }
func init() { http.HandleFunc("/", frontPageHandler) http.HandleFunc("/tiles", tileHandler) for i := range color { // Use a broader range of color for low intensities. if i < 255/10 { color[i] = image.RGBAColor{uint8(i * 10), 0, 0, 0xFF} } else { color[i] = image.RGBAColor{0xFF, 0, uint8(i - 255/10), 0xFF} } } tmpl := template.New(nil) tmpl.SetDelims("{{", "}}") if err := tmpl.ParseFile("map.html"); err != nil { frontPage = []byte("tmpl.ParseFile failed: " + err.String()) return } b := new(bytes.Buffer) data := map[string]interface{}{ "InProd": !appengine.IsDevAppServer(), } if err := tmpl.Execute(b, data); err != nil { frontPage = []byte("tmpl.Execute failed: " + err.String()) return } frontPage = b.Bytes() }
func handler(w http.ResponseWriter, r *http.Request) { name := r.FormValue("name") htmltemplate := template.Must(template.New("html").Parse(templateHTML)) err := htmltemplate.Execute(w, name) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } }
func init() { frontPage = template.New(nil) frontPage.SetDelims("«", "»") if err := frontPage.Parse(frontPageText); err != nil { panic(err) } output = template.MustParse(outputText, nil) }
func parse(s string) *template.Template { t := template.New(nil) t.SetDelims("〈", "〉") if err := t.Parse(s); err != nil { panic(s) } return t }
func ParseTemp(file string) { mainTemplate = template.New(nil) mainTemplate.SetDelims("{{", "}}") if err := mainTemplate.ParseFile(file); err != nil { mainTemplateErr = fmt.Errorf("tmpl.ParseFile failed: %v", err) return } }
func init() { EditorT = template.New(nil) EditorT.SetDelims("{{", "}}") EditorT.ParseFile(EditorTemplatePath) BuildBarT = template.New(nil) BuildBarT.SetDelims("{{", "}}") BuildBarT.ParseFile(BuildBarTemplatePath) PkgInfoT = template.New(nil) PkgInfoT.SetDelims("{{", "}}") PkgInfoT.ParseFile(PkgInfoTemplatePath) BuildT = template.New(nil) BuildT.SetDelims("{{", "}}") BuildT.ParseFile(BuildTemplatePath) }
func main() { chatTempl = template.Must(template.New("chat").Parse(chatStr)) go hub() server.Run(":8080", web.NewRouter(). Register("/", "GET", chatFrameHandler). Register("/ws", "GET", chatWsHandler)) }
func BenchmarkEscapedExecute(b *testing.B) { tmpl := template.Must(Escape(template.Must(template.New("t").Parse(`<a onclick="alert('{{.}}')">{{.}}</a>`)))) var buf bytes.Buffer b.ResetTimer() for i := 0; i < b.N; i++ { tmpl.Execute(&buf, "foo & 'bar' & baz") buf.Reset() } }
func init() { for _, name := range []string{"500", "404", "report"} { tmpl := template.Must(template.New(name).ParseFile("jshint/templates/" + name + ".html")) templates[name] = tmpl } http.HandleFunc("/reports/save/", save) http.HandleFunc("/reports/", show) http.HandleFunc("/", notFound) }