func init() { // Articles goweb.MapRest("/article/category/{category_id}", new(controller.ArticleController)) // Articles goweb.MapRest("/article", new(controller.ArticleController)) // Comments goweb.MapRest("/comment", new(controller.CommentController)) // Categories goweb.MapRest("/category", new(controller.CategoryController)) // Logs goweb.MapRest("/log", new(controller.LogController)) // Search goweb.MapRest("/search", new(controller.SearchController)) // Documentation wadl goweb.MapFunc("/documentation/wadl", func(c *goweb.Context) { var docTemplate = template.Must(template.ParseFile("webservice/views/wadl.wadl")) if err := docTemplate.Execute(c.ResponseWriter, nil); err != nil { c.RespondWithErrorMessage(err.String(), http.StatusInternalServerError) } }) // WADL in XML voor XML viewer goweb.MapFunc("/documentation/wadl/xml", func(c *goweb.Context) { var docTemplate = template.Must(template.ParseFile("webservice/views/wadl.xml")) if err := docTemplate.Execute(c.ResponseWriter, nil); err != nil { c.RespondWithErrorMessage(err.String(), http.StatusInternalServerError) } }) // Documentation goweb.MapFunc("/documentation", func(c *goweb.Context) { var docTemplate = template.Must(template.ParseFile("webservice/views/documentation.html")) if err := docTemplate.Execute(c.ResponseWriter, nil); err != nil { c.RespondWithErrorMessage(err.String(), http.StatusInternalServerError) } }) // Index goweb.MapFunc("/", func(c *goweb.Context) { var indexTemplate = template.Must(template.ParseFile("webservice/views/index.html")) if err := indexTemplate.Execute(c.ResponseWriter, nil); err != nil { c.RespondWithErrorMessage(err.String(), http.StatusInternalServerError) } }) // use the default Go handler http.Handle("/", goweb.DefaultHttpHandler) }
// Get a template by filename and refresh if in development mode func getTemplateFunc(filename string) func() *template.Template { t, err := template.ParseFile(filename) if err != nil { log.Fatalf("Error parsing template: %v", err) } return func() *template.Template { if Development { t, err = template.ParseFile(filename) if err != nil { log.Printf("Error parsing template: %v", err) } } return t } }
func main() { prepareCache() queryString := parseQueryString(os.Getenv("QUERY_STRING")) fmap := template.FormatterMap{"html": template.HTMLFormatter} opts := map[string](interface{}){} os.Stdout.WriteString("Content-type: text/html\n\n") conn := db.PrepareConnection(Cache["db"]) hdr, _ := template.ParseFile(Cache["tpl:headr"], fmap) tmpl := new(template.Template) if queryString["forum"] != "" { tmpl, _ = template.ParseFile(Cache["tpl:forum"], fmap) opts["forum"] = db.Get(conn, db.Forum{}, queryString["forum"]) } else { tmpl, _ = template.ParseFile(Cache["tpl:index"], fmap) } _ = strconv.Itoa c, _ := conf.ReadConfigFile(path.Join(Cache["wd"], "flow.config")) opts["version"] = Version opts["title"], _ = c.GetString("default", "boardName") defer conn.Close() if !db.TablesExist(conn) { db.SetupForum(conn) } stmt, _ := conn.Prepare("SELECT id, name, desc FROM forum;") db.HandleError(stmt.Exec()) forums := []db.Forum{} if stmt.Next() { var f db.Forum db.HandleError(stmt.Scan(&f.Id, &f.Name, &f.Desc)) forums = append(forums, f) } opts["forums"] = forums opts["cwd"] = Cache["cwdir"] hdr.Execute(opts, os.Stdout) tmpl.Execute(opts, os.Stdout) }
func EnterRollOff(w http.ResponseWriter, r *http.Request) { id := r.URL.Path[len("/roll-off-entry/"):] fmt.Println("User wishes to enter rolloff ", id) rollingUser := ParseUser(r) entry := &RollOffEntry{User: rollingUser, Score: rand.Intn(100) + 1} for _, r := range rolloffs { fmt.Println("Checking rolloff ", r.Id) if r.Id == id { r.AddEntry(entry) for elem := room.Users.Front(); elem != nil; elem = elem.Next() { go func(e *list.Element) { var tName string u := e.Value.(*User) if u == rollingUser { tName = "templates/roll-off/user-joins.html" } else { tName = "templates/roll-off/other-user-joins.html" } t := template.Must(template.ParseFile(tName)) m := NewMessage("system", "", "system") t.Execute(m, entry) u.c <- m }(elem) } } } }
func loadTemplates() (err os.Error) { PatientsTable, err = template.ParseFile("assets/patients.tpl", nil) if err != nil { log.Println("ERROR: Loading patients.tpl", err) return err } log.Println("LOG: patients.tpl Loaded") PatientsPage, err = template.ParseFile("assets/page.tpl", nil) if err != nil { log.Println("ERROR: Loading page.tpl", err) return err } log.Println("LOG: page.tpl Loaded") return nil }
func NewRollOff(w http.ResponseWriter, r *http.Request) { rollingUser := ParseUser(r) entry := &RollOffEntry{User: rollingUser, Score: rand.Intn(100) + 1} rolloff := &RollOff{Id: randomString(20), Open: true} rolloff.AddEntry(entry) go rolloff.Cycle() rolloffs = append(rolloffs, rolloff) for elem := room.Users.Front(); elem != nil; elem = elem.Next() { go func(e *list.Element) { var tName string u := e.Value.(*User) if u == rollingUser { tName = "templates/roll-off/rolling-user.html" } else { tName = "templates/roll-off/other-users.html" } t := template.Must(template.ParseFile(tName)) m := NewMessage("system", "", "system") t.Execute(m, entry) u.c <- m }(elem) } }
func HandleHome(writer http.ResponseWriter, request *http.Request) { if request.URL.Path == "/" { temp, err := template.ParseFile("html/index.html") if err != nil { write_error(writer, err) return } temp.Execute(writer, &Page{}) } else { var err os.Error var is_raw = false var raw_prefix = "/raw/" var urlid string if strings.Contains(request.URL.Path, raw_prefix) { is_raw = true urlid = request.URL.Path[len(raw_prefix):] } else { urlid = request.URL.Path[1:] } page, err := GetPageFromDataStore(urlid, request) if err != nil { write_error(writer, err) return } if is_raw { RenderPageRaw(page, writer) } else { err = RenderPage(page, writer) if err != nil { write_error(writer, err) return } } } }
func loadTemplate(tname string) *templateInfo { cached := templateCache[tname] if cached == nil { cached = &templateInfo{tpl: nil, mtime: 0, err: "Not loaded"} } // Check mtime. fin, err := os.Open(tname) if err != nil { cached.err = fmt.Sprintf("Unable to open '%s': '%v'", tname, err) return cached } defer fin.Close() stat, err := fin.Stat() if err != nil { cached.err = fmt.Sprintf("Unable to stat '%s': '%v'", tname, err) return cached } if stat.Mtime_ns <= cached.mtime { return cached } cached.tpl, err = template.ParseFile(tname) if err == nil { cached.err = "" } else { cached.err = fmt.Sprintf("Error while parsing '%s': '%v'", tname, err) } templateCache[tname] = cached return cached }
func viewHandle(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFile("templates/view.html") if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } t.Execute(w, p) }
func GeneratePresentation(name, theme string) { if dir, err := os.Getwd(); err == nil { out := path.Join(dir, "out", name) tDir := path.Join(dir, "themes", theme) CopyDir(out, path.Join(dir, "resources")) CopyDir(path.Join(out, "theme"), tDir) templates := map[string] string{ "cfg.tpl": fmt.Sprintf("%s.cfg", name), "fabfile.py.tpl": "fabfile.py", "rst.tpl": fmt.Sprintf("%s.rst", name), } data := &TemplateData{name} templatesDir := path.Join(dir, "templates") for k, v := range templates { t, err := template.ParseFile(path.Join(templatesDir, k)) if err != nil { panic(err) } dstFile, _ := os.Create(path.Join(out, v)) defer dstFile.Close() t.Execute(dstFile, data) } } }
// parse a file, and store the templates in Page.Template func (t *Page) ParseFile(formatterMap map[string]func(io.Writer, string, ...interface{})) { var err os.Error t.Template, err = template.ParseFile(t.Filename, formatterMap) if err != nil { log.Fatal("Cannot Parse " + t.Filename + "; got " + err.String()) } }
func RenderPage(page *Page, writer http.ResponseWriter) os.Error { temp, err := template.ParseFile("html/paste.html") if err != nil { return err } temp.Execute(writer, page) return nil }
func root(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) clientTemplate := template.Must(template.ParseFile("client.html")) token_value := strconv.Itoa(rand.Int()) token_key, _ := channel.Create(c, token_value) clientTemplate.Execute(w, token_key) map_clients[token_key] = token_value }
func writeTemplate(w http.ResponseWriter, tempFile string, model interface{}) { if tpl, err := template.ParseFile(tempFile); err != nil { fmt.Fprintf(w, "Internal Server Error") w.WriteHeader(500) } else { tpl.Execute(w, model) } }
func logViewHandle(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFile("templates/logview.html") if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } pkg := r.URL.Path[9:] t.Execute(w, p.Entries[pkg]) }
func editHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[lenPath:] p, err := loadPage(title) if err != nil { p = &Page{Title: title} } t, _ := template.ParseFile("edit.html", nil) t.Execute(w, p) }
func TemplateRender(w http.ResponseWriter, filename string, context interface{}) { t, err := template.ParseFile(filename, nil) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } if err := t.Execute(w, context); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } }
func (this *TemplateCache) Load(root string) (err os.Error) { var fd *os.File if fd, err = os.Open(root, os.O_RDONLY, 0600); err != nil { return } var dirs []os.FileInfo if dirs, err = fd.Readdir(-1); err != nil { fd.Close() return } fd.Close() var p string var ok bool var tmpl *template.Template for _, sd := range dirs { p = path.Join(root, sd.Name) if sd.IsDirectory() { if err = this.Load(p); err != nil { return } } else { if tmplExt != path.Ext(p) { continue } fmt.Fprintf(os.Stdout, "[i] Parsing template: %s\n", p) if tmpl, err = template.ParseFile(p, nil); err != nil { return } // Strip webroot and extension p = p[len(context.Config().WebRoot):] p = p[0 : len(p)-len(tmplExt)] if len(p) == 0 { return os.NewError("Invalid template name") } this.lock.RLock() if _, ok = this.data[p]; ok { this.lock.RUnlock() return os.NewError("Duplicate template definition: " + p) } this.lock.RUnlock() this.lock.Lock() this.data[p] = tmpl this.lock.Unlock() } } return }
func ppPlace(place *Place) { home := os.Getenv("HOME") t, err := template.ParseFile(path.Join(home, ".lunch", templateFile), nil) if err != nil { fmt.Println(place.String()) return } t.Execute(place, os.Stdout) }
func renderPage(w http.ResponseWriter, data map[string]string) { mainPageTemplate, templateErr := template.ParseFile("hvadsigeralex/templates/index.html") if templateErr != nil { http.Error(w, templateErr.String(), http.StatusInternalServerError) } err := mainPageTemplate.Execute(w, data) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } }
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { t, err := template.ParseFile(tmpl+".html", nil) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } err = t.Execute(w, p) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } }
func spamham(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) requireLogin(c, w, r.URL.String()) mainPageTemplate, templateErr := template.ParseFile("templates/spamham.html") if templateErr != nil { http.Error(w, templateErr.String(), http.StatusInternalServerError) } err := mainPageTemplate.Execute(w, nil) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } }
func searchHandler(w http.ResponseWriter, r *http.Request) { context := &Search{} // prepare the template t, err := template.ParseFile("template/search.html") if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } context.T = t ae := appengine.NewContext(r) query := r.FormValue("q") queryLength := len([]int(query)) // unicode length // max 8 letters if queryLength > 8 { query = query[0:8] http.Redirect(w, r, fmt.Sprintf("search?q=%s", query), 302) return } // lowercase only if query != strings.ToLower(query) { http.Redirect(w, r, fmt.Sprintf("search?q=%s", strings.ToLower(query)), 302) return } context.Q = query hashTable := make(map[string]byte, 0) if 0 != queryLength { if queryLength > 8 { query = query[0:8] } // make sure enable is loaded var e *word.Enable var err os.Error if e, err = loadEnable(); err != nil { ae.Errorf("%v", err) } channel := word.StringPermutations(query) for p := range channel { if valid := e.WordIsValid(p); !valid { continue } if _, inHash := hashTable[p]; !inHash { context.Permutations = append(context.Permutations, p) hashTable[p] = 1 } } } // display template if err := context.T.Execute(w, context); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } }
func DraftsServer(w http.ResponseWriter, req *http.Request) { draftsInfo, err := ioutil.ReadDir(DRAFTS_DIR) if err != nil { log.Fatal(err) } template, err := template.ParseFile("templates/drafts.html") if err != nil { log.Fatal(err) } err = template.Execute(w, draftsInfo) if err != nil { log.Fatal(err) } }
func renderTmpl(ctx *web.Context, tmpl, title, body string) { d := map[string]string{ "prefix": urlPrefix, "title": title, "body": body, } t, err := template.ParseFile("tmpl/"+tmpl+".html", nil) if err != nil { ctx.Abort(500, "Unable to Parse template file: "+err.String()) return } err = t.Execute(ctx, d) if err != nil { ctx.Abort(500, "Unable to Execute template: "+err.String()) } }
func Redirect(w http.ResponseWriter, r *http.Request) { key := r.URL.Path[1:] if key == "favicon.ico" { http.NotFound(w, r) } else if key == "" { logo := &Title{Logo: "You.RL"} tpl, _ := template.ParseFile("index.html", nil) tpl.Execute(w, logo) } else if key == "index.js" { http.ServeFile(w, r, "index.js") } else { var url string store.Get(&key, &url) http.Redirect(w, r, url, http.StatusFound) } }
func index(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) u := user.Current(c) if u != nil { w.Header().Set("Location", "/spamham") w.WriteHeader(http.StatusFound) return } loginUrl, _ := user.LoginURL(c, r.URL.String()) mainPageTemplate, templateErr := template.ParseFile("templates/index.html") if templateErr != nil { http.Error(w, templateErr.String(), http.StatusInternalServerError) } err := mainPageTemplate.Execute(w, loginUrl) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } }
func loginGet(w http.ResponseWriter, r *http.Request) { responseType, client, err := params(r) if err != nil { err.WriteTo(w) return } loginTemplate := template.Must(template.ParseFile("fragspace/oauth2/login.xhtml")) loginModel := &LoginModel{ responseType, client.Id, slicelib.Filter(strings.Split(r.FormValue("msgs"), "|"), slicelib.IsNonEmpty), } if err := loginTemplate.Execute(w, loginModel); err != nil { c := appengine.NewContext(r) c.Errorf("%v", err) http.Error(w, err.String(), http.StatusInternalServerError) } }
func viewHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[lenPath:] p, err := loadPage(title) if err != nil { p = &Page{Title: title} } t, _ := template.ParseFile("view.html", nil) t.Execute(w, p) db, err := mysql.DialUnix(mysql.DEFAULT_SOCKET, "user", "password", "database") if err != nil { os.Exit(1) } if db != nil { os.Exit(1) } }
func main() { runtime.GOMAXPROCS(8) port := "0.0.0.0:8000" room = NewRoom() rolloffs = make([]*RollOff, 0) staticDir := http.Dir("/projects/go/chat/static") staticServer := http.FileServer(staticDir) homeTemplate = template.Must(template.ParseFile("templates/index.html")) http.HandleFunc("/", LogWrap(Home, "Home")) http.HandleFunc("/feed", LogWrap(FeedMux, "FeedMux")) http.HandleFunc("/login", LogWrap(LoginMux, "LoginMux")) http.HandleFunc("/users", LogWrap(GetUsers, "GetUsers")) http.HandleFunc("/roll", LogWrap(Roll, "Roll")) http.HandleFunc("/roll-off", LogWrap(NewRollOff, "NewRollOff")) http.HandleFunc("/roll-off-entry/", LogWrap(EnterRollOff, "EnterRollOff")) http.Handle("/static/", http.StripPrefix("/static", staticServer)) fmt.Printf("Serving at %s ----------------------------------------------------\n", port) http.ListenAndServe(port, nil) }