func main() { // Pull in command line options or defaults if none given flag.Parse() f, err := os.OpenFile(*skylib.LogFileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) if err == nil { defer f.Close() log.SetOutput(f) } skylib.Setup(sName) homeTmpl = template.MustParse(homeTemplate, nil) respTmpl = template.MustParse(responseTemplate, nil) rpc.HandleHTTP() portString := fmt.Sprintf("%s:%d", *skylib.BindIP, *skylib.Port) stack := new(mango.Stack) stack.Address = portString routes := make(map[string]mango.App) routes["/"] = homeHandler routes["/new"] = submitHandler stack.Middleware(mango.Routing(routes)) stack.Run(nil) }
func main() { var err os.Error // Pull in command line options or defaults if none given flag.Parse() f, err := os.OpenFile(*skylib.LogFileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) if err == nil { defer f.Close() log.SetOutput(f) } skylib.Setup(sName) homeTmpl = template.MustParse(homeTemplate, nil) respTmpl = template.MustParse(responseTemplate, nil) http.HandleFunc("/", homeHandler) http.HandleFunc("/new", submitHandler) rpc.HandleHTTP() portString := fmt.Sprintf("%s:%d", *skylib.BindIP, *skylib.Port) err = http.ListenAndServe(portString, nil) if err != nil { log.Fatal("ListenAndServe: ", err.String()) } }
func ShowErrors(templateString string) Middleware { if templateString == "" { templateString = ` <html> <body> <p> {Error|html} </p> </body> </html> ` } errorTemplate := template.MustParse(templateString, nil) 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 }{err.(string)}) status = 500 headers = Headers{} body = Body(buffer.String()) } }() return app(env) } }
func parseChunk(lines []string, lesson *Lesson) *Chunk { ret := &Chunk{Title: lines[0], ToC: make([]*ChunkSlide, 0, 10), Lesson: lesson} lines = lines[1:] ret.DescHTML, lines = parseText(lines, false, nil) ret.SRSItems = getSRSItems(lines) cont := "" partNum := 0 for len(lines) != 0 && (len(lines) != 1 || lines[0] != "") { if lines[0][0:7] != "\\slide:" { log.Panicf("Error : expected '\\slide:' directive in chunk file.") } slideTitle := lines[0][7:] lines = lines[1:] slideText, nl := parseText(lines, true, ret) lines = nl partNum++ cont += fmt.Sprintf(` <div class="slide" id="part%v" name="part%v"> <h1>%v</h1> %v </div> `, partNum, partNum, slideTitle, slideText) ret.ToC = append(ret.ToC, &ChunkSlide{partNum, slideTitle}) } // fmt.Printf(cont) //DEBUG ret.Contents = template.MustParse(cont, nil) return ret }
func init() { frontPage = template.New(nil) frontPage.SetDelims("«", "»") if err := frontPage.Parse(frontPageText); err != nil { panic(err) } output = template.MustParse(outputText, nil) }
func loadTemplate(path string) (t *template.Template, err os.Error) { if buf, readErr := io.ReadFile("templates/" + path); readErr == nil { t = template.MustParse(string(buf), template.FormatterMap{ "html": template.HTMLFormatter }); } else { err = readErr } return; }
func main() { // Pull in command line options or defaults if none given flag.Parse() skylib.NewAgent().Start() homeTmpl = template.MustParse(homeTemplate, nil) respTmpl = template.MustParse(responseTemplate, nil) portString := fmt.Sprintf("%s:%d", *skylib.BindIP, *skylib.Port) stack := new(mango.Stack) stack.Address = portString routes := make(map[string]mango.App) routes["/"] = homeHandler routes["/new"] = submitHandler stack.Middleware(mango.Routing(routes)) stack.Run(nil) }
func conventionCard(c http.ResponseWriter, p Settings) { fmt.Fprintln(c, `<script type="text/javascript"> function submitform() { document.forms["catchall"].submit(); } </script> `) e := template.MustParse(cctemplate, htmlcardformatter).Execute(p.Card(), c) if e != nil { fmt.Println("Template error:", e) } }
func main() { var err os.Error // Pull in command line options or defaults if none given flag.Parse() skylib.NewAgent().Start() homeTmpl = template.MustParse(homeTemplate, nil) respTmpl = template.MustParse(responseTemplate, nil) http.HandleFunc("/", homeHandler) http.HandleFunc("/new", submitHandler) portString := fmt.Sprintf("%s:%d", *skylib.BindIP, *skylib.Port) err = http.ListenAndServe(portString, nil) if err != nil { log.Fatal("ListenAndServe: ", err.String()) } }
// getTemplate returns a template at a given filepath. func getTemplate(filepath string) *template.Template { if templates[filepath] == nil { file, err := os.Open(template_dir+filepath, os.O_RDONLY, 0666) if err != nil { log.Exit("not exist: %s", filepath) } reader := bufio.NewReader(file) body, _ := reader.ReadString('~') tmpl := template.MustParse(body, nil) templates[filepath] = tmpl } return templates[filepath] }
func conventionCard(p Settings) string { buf := bytes.NewBuffer(make([]byte, 0, 4*1024)) fmt.Fprint(buf, `<script type="text/javascript"> function submitform() { document.forms["catchall"].submit(); } </script> `) e := template.MustParse(cctemplate, htmlcardformatter).Execute(p.Card(), buf) if e != nil { fmt.Fprintln(buf, "<h3>Template error:", e, `</h3>`) } return buf.String() }
func writePackagePage(pkgname string) { // TODO: I/O error checks pkgfilename := strings.Replace(pkgname, "/", "_", -1) dest := path.Join(*optOutDir, pkgfilename+".html") f, err := os.Create(dest) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer f.Close() bf := bufio.NewWriter(f) var packageTemplate = template.MustParse(packageTemplateStr, nil) tplparams := map[string]string{ "pkgname": pkgname, "datafile": "gortfm-" + pkgfilename + "-data.js", } packageTemplate.Execute(bf, tplparams) bf.Flush() }
func serveError(req *web.Request, status int, reason os.Error, header web.Header) { header.Set(web.HeaderContentType, "text/plain; charset=utf-8") w := req.Responder.Respond(status, header) io.WriteString(w, web.StatusText(status)) if reason != nil { io.WriteString(w, "\n") io.WriteString(w, reason.String()) } } var mainPage = template.MustParse(`<html><body> {.repeated section gg} {.section Author}<b>{@|html}</b>{.or}An anonymous person{.end} wrote <blockquote>{Content|html}</blockquote> {.end} <form action="/sign" method="POST"> <div><input type="hidden" name="xsrf" value="{xsrf}"> <textarea name="content" rows="3" cols="60"></textarea></div> <div><input type="submit" value="Sign Guestbook"></div> </form></body></html>`, nil) func handleMainPage(r *web.Request) { c := gae.Context(r) q := datastore.NewQuery("Greeting").Order("-Date").Limit(10) var gg []*Greeting _, err := q.GetAll(c, &gg) if err != nil { r.Error(web.StatusInternalServerError, err) return } w := r.Respond(200, "Content-Type", "text/html")
var makefileTemplate = template.MustParse(` include $(GOROOT)/src/Make.inc TARG={Targ} TARGDIR={TargDir} {.section GoFiles} GOFILES=\ {.repeated section @} {@}\ {.end} {.end} {.section OFiles} OFILES=\ {.repeated section @} {@}\ {.end} {.end} {.section CgoFiles} CGOFILES=\ {.repeated section @} {@}\ {.end} {.end} {.section CgoOFiles} CGO_OFILES=\ {.repeated section @} {@}\ {.end} {.end} GCIMPORTS={.repeated section Imports}-I "{@}" {.end} LDIMPORTS={.repeated section Imports}-L "{@}" {.end} include $(GOROOT)/src/Make.{Type} `, nil)
<html> <body> <h1>Who is on it?</h1> <h2>Current Emails</h2> <ul> {.repeated section @} <li><a href="/show?sender={Sender}&date={RecieptDate}">{Sender} - {Subject} - {RecieptDate}</a></li> {.or} Nothing to do. Good job. {.end} </ul> </body> </html> ` var rootTemplate = template.MustParse(root_template, nil) const show_template = ` <html> <body> {.repeated section @} <h1>{Subject|html}</h1> <h2>{Sender}</h2> <h3>Status</h3> <p>Received: {RecieptDate}</p> <p>Owner: {.section Owner}{Owner}</p> <p>Accepted On: {OwnerDate}{.or}Nobody{.end}</p> {.section ClosedDate} <p>Closed On: {ClosedDate}</p> {.end} <h3>Message Content</h3>
oauthClient.Credentials.Secret = m["ClientSecret"].(string) } func main() { flag.Parse() readSettings() h := web.FormHandler(10000, true, web.NewRouter(). Register("/", "GET", home). Register("/login", "GET", login). Register("/callback", "GET", authCallback)) server.Run(":8080", h) } var fmap = template.FormatterMap{"": template.HTMLFormatter} var homeLoggedOutTempl = template.MustParse(homeLoggedOutStr, fmap) const homeLoggedOutStr = ` <html> <head> </head> <body> <a href="/login"><img src="http://a0.twimg.com/images/dev/buttons/sign-in-with-twitter-d.png"></a> </body> </html>` var homeTempl = template.MustParse(homeStr, fmap) const homeStr = ` <html> <head>
files, _, err := goFiles(dir) if err != nil { return nil, err } var buf bytes.Buffer if err := makefileTemplate.Execute(&makedata{pkg, files}, &buf); err != nil { return nil, err } return buf.Bytes(), nil } // makedata is the data type for the makefileTemplate. type makedata struct { pkg string // package import path files []string // list of .go files } var makefileTemplate = template.MustParse(` include $(GOROOT)/src/Make.$(GOARCH) TARG={pkg} GOFILES=\ {.repeated section files} {@}\ {.end} include $(GOROOT)/src/Make.pkg `, nil)
"xsrf": req.Param.GetDef(web.XSRFParamName, ""), }, req.Respond(status, web.HeaderContentType, "text/html")) } func coreHandler(req *web.Request) { coreTempl.Execute(map[string]interface{}{ "req": req, "status": web.StatusOK, "message": "ok", "xsrf": req.Param.GetDef(web.XSRFParamName, ""), }, req.Respond(web.StatusOK, web.HeaderContentType, "text/html")) } var coreTempl = template.MustParse(coreStr, nil) const coreStr = ` <html> <head> <title>Core</title> </head> <body> <hr> Status: {status} {message} <hr> <a href="/core">/core</a><br> <a href="/core/a/blorg">/core/a/blorg</a><br> <a href="/core/a/foo?b=bar&c=quux">/core/a/foo?b=bar&c=quux</a><br> <a href="/core/a/blorg/">/core/a/blorg/</a><br> <a href="/core/b/foo/c/bar">/core/b/foo/c/bar</a><br>
"status": status, "message": reason, "xsrf": req.Param.Get(web.XSRFParamName), }) } func coreHandler(req *web.Request) { coreTempl.Execute( req.Respond(web.StatusOK, web.HeaderContentType, "text/html"), map[string]interface{}{ "req": req, "status": web.StatusOK, "message": "ok", "xsrf": req.Param.Get(web.XSRFParamName), }) } var coreTempl = template.MustParse(coreStr, template.FormatterMap{"": template.HTMLFormatter}) const coreStr = ` <html> <head> <title>Gopher Times</title> </head> <body> <hr> Status: {status} {message} We're sorry, but there was a problem fulfilling your request. </body> </html> `
import ( "doozer/store" "doozer/util" "http" "io" "json" "log" "net" "strings" "template" "websocket" ) var Store *store.Store var ClusterName, evPrefix string var mainTpl = template.MustParse(main_html, nil) type info struct { Path string } type stringHandler struct { contentType string body string } func (sh stringHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.SetHeader("content-type", sh.contentType) io.WriteString(w, sh.body) }
q := datastore.NewQuery("Log").Order("-Date").Limit(10) greetings := make([]Log, 0, 10) if _, err := q.GetAll(c, &greetings); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } if err := guestbookTemplate.Execute(w, greetings); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } } func dstimeFormatter(wr io.Writer, formatter string, dstime ...interface{}) { io.WriteString(wr, time.SecondsToUTC(int64(dstime[0].(datastore.Time))/1000000).Format(time.RFC1123)) } var guestbookTemplate = template.MustParse(guestbookTemplateHTML, template.FormatterMap{"dstime": dstimeFormatter}) const guestbookTemplateHTML = ` <html> <body> <ul> {.repeated section @} <li> {.section User} <b>{@|html}</b> accessed at: {.or} An anonymous person FOOBAZED at: {.end} {Date|dstime|html} from {RemoteAddress|html} {.end} </ul>
func loadExtendedTemplate(dir, name string) *template.Template { t := &extendedTemplate{dir, make(map[string][]string), make(map[string]bool)} t.load(name) contents := t.resolve("main") return template.MustParse(contents, nil) }
func main() { sqlite3.Initialize() defer func() { log.Stdout("closing sqlite3") sqlite3.Shutdown() }() dbh := new(sqlite3.Handle) dbh.Open("bbs.db") defer dbh.Close() InitTables(dbh) flag.Parse() templ := func() *template.Template { templateStr, err := io.ReadFile("tmpl/top.tmpl") if err != nil { log.Exit(err) } return template.MustParse(string(templateStr), nil) }() http.Handle("/", http.HandlerFunc(func(c *http.Conn, req *http.Request) { params := new(struct{ msgs []string }) storage := new(vector.StringVector) func() { st, err := dbh.Prepare("SELECT * from entry ORDER BY id DESC limit 30;") func() { if err != "" { log.Exit(err) } for { rv := st.Step() switch { case rv == sqlite3.SQLITE_DONE: return case rv == sqlite3.SQLITE_ROW: body := st.ColumnText(1) storage.Push(body) default: println(rv) log.Exit(dbh.ErrMsg()) } } }() if st.Finalize() != sqlite3.SQLITE_OK { log.Exit(dbh.ErrMsg()) } }() params.msgs = storage.Data() err := templ.Execute(params, c) if err != nil { log.Exit("templ.Execute:", err) } })) http.Handle("/post", http.HandlerFunc(func(c *http.Conn, req *http.Request) { req.ParseForm() body := req.Form["body"][0] st, err := dbh.Prepare("INSERT INTO entry (body) VALUES (?)") if err != "" { log.Exit(err) } if st.BindText(1, body) != sqlite3.SQLITE_OK { log.Exit("cannot bind: ", dbh.ErrMsg()) } if st.Step() != sqlite3.SQLITE_DONE { log.Exit(dbh.ErrMsg()) } if st.Finalize() != sqlite3.SQLITE_OK { log.Exit(dbh.ErrMsg()) } http.Redirect(c, "/", 302) })) http.Handle("/css/", http.HandlerFunc(func(c *http.Conn, req *http.Request) { http.ServeFile(c, req, "."+req.URL.Path) })) // run httpd func() { fmt.Printf("http://%s/\n", *addr) err := http.ListenAndServe(*addr, nil) if err != nil { log.Exit("ListenAndServe:", err) } }() }
package main import ( "flag" "http" "io" "log" "template" ) var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18 var fmap = template.FormatterMap{ "html": template.HTMLFormatter, "url+html": UrlHtmlFormatter, } var templ = template.MustParse(templateStr, fmap) func main() { flag.Parse() http.Handle("/", http.HandlerFunc(QR)) err := http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe:", err) } } func QR(w http.ResponseWriter, req *http.Request) { templ.Execute(w, req.FormValue("s")) } func UrlHtmlFormatter(w io.Writer, fmt string, v ...interface{}) {
Register("/core/a/<a>/", "GET", coreHandler). Register("/core/b/<b>/c/<c>", "GET", coreHandler). Register("/core/c", "POST", coreHandler))))) listener, err := net.Listen("tcp", ":8080") if err != nil { log.Fatal("Listen", err) return } defer listener.Close() err = (&server.Server{Listener: listener, Handler: h, Logger: server.LoggerFunc(server.VerboseLogger)}).Serve() if err != nil { log.Fatal("Server", err) } } var homeTempl = template.MustParse(homeStr, template.FormatterMap{"": template.HTMLFormatter}) const homeStr = ` <html> <head> </head> <body> <ul> <li><a href="/core">Core functionality</a> <li><a href="/chat">Chat using WebSockets</a> <li><a href="/mp">Multipart Form</a> </ul> </body> </html>`
"io" "os" "template" "appengine" "appengine/blobstore" ) func serveError(c appengine.Context, w http.ResponseWriter, err os.Error) { w.WriteHeader(http.StatusInternalServerError) w.Header().Set("Content-Type", "text/plain") io.WriteString(w, "Internal Server Error") c.Errorf("%v", err) } var rootTemplate = template.MustParse(rootTemplateHTML, nil) const rootTemplateHTML = ` <html><body> <form action="{@}" method="POST" enctype="multipart/form-data"> Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html> ` func handleRoot(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) uploadURL, err := blobstore.UploadURL(c, "/upload", nil) if err != nil { serveError(c, w, err) return
Service {Name} <hr> <table> <th align=center>Method</th><th align=center>Calls</th> {.repeated section Method} <tr> <td align=left font=fixed>{Name}({Type.ArgType}, {Type.ReplyType}) os.Error</td> <td align=center>{Type.NumCalls}</td> </tr> {.end} </table> {.end} </body> </html>` var debug = template.MustParse(debugText, nil) type debugMethod struct { Type *methodType Name string } type methodArray []debugMethod type debugService struct { Service *service Name string Method methodArray } type serviceArray []debugService
"http" "io" "json" "log" "net" "runtime" "strings" "template" "websocket" ) var Store *store.Store var ClusterName string var ( mainTpl = template.MustParse(main_html, nil) statsTpl = template.MustParse(stats_html, nil) ) type info struct { Name string Path string } type stringHandler struct { contentType string body string } func (sh stringHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("content-type", sh.contentType)
// TODO: cache strategy // TODO: learn best practice for reading template file into string and parsing // TODO: check error from ReadFile // TODO: synchronized cache for multithreading func get_template(s string) *template.Template { var templateBytes, _ = io.ReadFile(s); var templateBuffer = bytes.NewBuffer(templateBytes); var templateStr = templateBuffer.String(); return template.MustParse(templateStr, fmap); }
var homePage = template.MustParse( page( "Go Paste!", Div( Form( Fieldset( Textarea("").Attrs(As{ "class": "paste-input", "rows": "30", "name": "code", }), Ul( Li( A("All Pastes").Attrs(As{ "href": "/all", })), Li( A("Source Code").Attrs(As{ "href": "http://github.com/vito/go-play/tree/master/gopaste", })), Li(""), Li("Tab key inserts tabstops."), Li("Seperate content with ---."), Li("Mod+S to submit."), Li( Input().Attrs(As{ "type": "checkbox", "class": "paste-private", "name": "private", }), "Private")).Attrs(As{ "class": "paste-notes", }), Input().Attrs(As{ "class": "paste-submit", "type": "submit", "value": "Go Paste!", "accesskey": "s", }))).Attrs(As{ "action": "/add", "method": "POST", })).Attrs(As{ "id": "home", })), fmap)