func postedHandler(s Services, w http.ResponseWriter, r *http.Request) { user, err := getUser(s, w, r) if err != nil { // TODO don't leak errors renderError(w, fmt.Sprintf("%s", err)) return } if user == nil { renderError(w, "You aren't logged in!") return } tweets, err := getTweets(s, *user, true) if err != nil { renderError(w, fmt.Sprintf("%s", err)) return } args := map[string]interface{}{ "posted": "yes", "username": user.screenName, "tweets": tweets, } data := mustache.RenderFileInLayout( "/usr/share/tweetautofeeder/templates/posted_page.must", "/usr/share/tweetautofeeder/templates/layout.must", args) w.Write([]byte(data)) return }
// LoginHandler writes out login template func LoginHandler(r *http.Request, w http.ResponseWriter) { context := map[string]interface{}{ "title": "Access magnet", "csrf_token": nosurf.Token(r), } w.Write([]byte(mustache.RenderFileInLayout("templates/login.mustache", "templates/base.mustache", context))) }
func DiscoverHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) vineApi := VineRequest{c} db := DB{c} var recentUsers []*VineUser var recentVerified []StoredUserMeta recent := datastore.NewQuery("Queue").Order("-Discovered").Limit(5).KeysOnly() k, _ := recent.GetAll(c, nil) for i, _ := range k { user, err := vineApi.GetUser(strconv.FormatInt(k[i].IntID(), 10)) if err == nil { recentUsers = append(recentUsers, user) } } verified := datastore.NewQuery("UserMeta").Filter("Verified =", true).Limit(5).KeysOnly() k, _ = verified.GetAll(c, nil) for i, _ := range k { user, err := db.GetUserMeta(k[i].IntID()) if err == nil { recentVerified = append(recentVerified, user.(StoredUserMeta)) } } data := map[string]interface{}{"recentUsers": recentUsers, "recentVerified": recentVerified} dir := path.Join(os.Getenv("PWD"), "templates") discover := path.Join(dir, "discover.html") layout := path.Join(dir, "pageLayout.html") page := mustache.RenderFileInLayout(discover, layout, data) fmt.Fprint(w, page) }
func DonateHandler(w http.ResponseWriter, r *http.Request) { dir := path.Join(os.Getenv("PWD"), "templates") donate := path.Join(dir, "donate.html") layout := path.Join(dir, "pageLayout.html") page := mustache.RenderFileInLayout(donate, layout, nil) fmt.Fprint(w, page) }
func listHosts(store configstore.Store, w http.ResponseWriter, req *http.Request) { names, err := store.Names() if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } if req.Header.Get("Accept") == "application/json" { w.Header().Set("Content-type", "application/json") enc := json.NewEncoder(w) err := enc.Encode(struct { Hostnames []string }{ Hostnames: names, }) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } } else { io.WriteString(w, mustache.RenderFileInLayout("templates/hosts.html.mustache", "templates/layout.html.mustache", names)) } }
func renderPage(ctx *web.Context) string { home := new(Home) user := ctx.Params["user"] followedBy, following, err := GetFollow(user) if err != nil { print(err.Error() + " in renderPage ") } jits, err := GetJits(user) if err != nil { print(err.Error() + " in renderPage jiterror ") } home.CardRender = FetchUserInfo(user) home.StreamRender = &Stream{UserID: user, Items: jits} //home.StreamRender = &Stream{UserID: user, Items: []*StreamItem{ // dummyStreamItem(), dummyStreamItem()}} home.FollowRender = new(Follow) home.FollowRender.UserID = user home.FollowRender.FollowedBy = followedBy home.FollowRender.Following = following compileHome(home) home.Html = mustache.RenderFileInLayout("Pages/Home.mustache", "Pages/layout.mustache", home) return home.Html }
func contact(w http.ResponseWriter, r *http.Request) { var submitted string if r.Method == "POST" { c := appengine.NewContext(r) name := r.FormValue("name") email := r.FormValue("email") info := r.FormValue("info") if name == "" || email == "" || info == "" { submitted = "Submission failed. Please enter all the information on the form. Thanks!" } else { msg := &mail.Message{ Sender: "*****@*****.**", To: []string{"*****@*****.**"}, Subject: fmt.Sprintf("Website Contact - %s", name), Body: fmt.Sprintf("Name: %s\nEmail: %s\nInformation: %s", name, email, info), HTMLBody: fmt.Sprintf("<html><body><p>Name: %s</p><p>Email: %s</p><p>Information: %s</p></body></html>", name, email, info), } if err := mail.Send(c, msg); err != nil { c.Errorf("Could not send email: %v", err) submitted = "Your information could not be sent. Could you try again later? Apologies!" } else { submitted = "Your information has been sent. I'll get back to you as soon as possible!" } } c.Infof("Contact submitted: name=%s, email=%s, info=%s", name, email, info) } out := mustache.RenderFileInLayout("mustache/contact.html.mustache", "mustache/layout.html.mustache", map[string]string{"submitted": submitted}) fmt.Fprint(w, out) }
func diffBackup(store configstore.Store, w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) t1, err := time.Parse(file.DefaultDateFormat, vars["date1"]) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } t2, err := time.Parse(file.DefaultDateFormat, vars["date2"]) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } e1 := configstore.Entry{ Name: vars["hostname"], Date: t1, } e2 := configstore.Entry{ Name: vars["hostname"], Date: t2, } err = store.Get(&e1) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } err = store.Get(&e2) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } dmp := diffmatchpatch.New() diffs := dmp.DiffMain(e1.Content.String(), e2.Content.String(), true) em := struct { Hostname string Date1 time.Time Date2 time.Time Diff string }{ vars["hostname"], t1, t2, dmp.DiffPrettyHtml(diffs), } io.WriteString(w, mustache.RenderFileInLayout("templates/diff.html.mustache", "templates/layout.html.mustache", em)) }
func NotFoundHandler(w http.ResponseWriter, r *http.Request) { dir := path.Join(os.Getenv("PWD"), "templates") notFound := path.Join(dir, "404.html") layout := path.Join(dir, "pageLayout.html") data := map[string]string{"url": r.RequestURI} page := mustache.RenderFileInLayout(notFound, layout, data) w.WriteHeader(404) fmt.Fprint(w, page) }
func homeHandler(w http.ResponseWriter, r *http.Request) { data.Title = "Home" data.Posts = make([]Post, 5) for k, v := range posts[:5] { data.Posts[k] = *v data.Posts[k].PrettyDate = humanize.Time(v.Date) } fmt.Fprint(w, mustache.RenderFileInLayout("templates/home.html.mustache", "templates/layout.html.mustache", data)) }
func hostBackup(store configstore.Store, w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) t, err := time.Parse(file.DefaultDateFormat, vars["date"]) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } e := configstore.Entry{ Name: vars["hostname"], Date: t, } err = store.Get(&e) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } if req.Header.Get("Accept") == "application/json" { w.Header().Set("Content-type", "application/json") enc := json.NewEncoder(w) err := enc.Encode(struct { Hostname string Date string Content string }{ Hostname: e.Name, Date: e.Date.Format(file.DefaultDateFormat), Content: e.Content.String(), }) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } } else { em := struct { Hostname string Date string Content string }{ vars["hostname"], t.String(), e.Content.String(), } io.WriteString(w, mustache.RenderFileInLayout("templates/entry.html.mustache", "templates/layout.html.mustache", em)) } }
func renderError(w http.ResponseWriter, errorMessage string) { data := mustache.RenderFileInLayout( "/usr/share/tweetautofeeder/templates/error_page.must", "/usr/share/tweetautofeeder/templates/layout.must", map[string]string{ "errorMessage": errorMessage, }) w.Write([]byte(data)) w.WriteHeader(http.StatusBadRequest) return }
func loginHandler(s Services, w http.ResponseWriter, r *http.Request) { url, _ := s.router.Get("login_begin").URLPath() data := mustache.RenderFileInLayout( "/usr/share/tweetautofeeder/templates/main_page.must", "/usr/share/tweetautofeeder/templates/layout.must", map[string]string{"url": url.String()}) w.Write([]byte(data)) return }
func listDates(store configstore.Store, w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) datesStore, err := store.Dates(vars["hostname"]) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } if req.Header.Get("Accept") == "application/json" { w.Header().Set("Content-type", "application/json") var dates []string for _, date := range datesStore { dates = append(dates, date.Format(file.DefaultDateFormat)) } enc := json.NewEncoder(w) err := enc.Encode(struct { Hostname string Dates []string }{ Hostname: vars["hostname"], Dates: dates, }) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } } else { var data = struct { Hostname string Dates []struct { String string URL string } }{ Hostname: vars["hostname"], } for _, date := range datesStore { data.Dates = append(data.Dates, struct { String string URL string }{ String: date.String(), URL: date.Format(file.DefaultDateFormat), }) } io.WriteString(w, mustache.RenderFileInLayout("templates/dates.html.mustache", "templates/layout.html.mustache", data)) } }
func TopHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) db := DB{c} dir := path.Join(os.Getenv("PWD"), "templates") top := path.Join(dir, "top.html") layout := path.Join(dir, "pageLayout.html") data := db.GetTop() data["LastUpdated"] = db.GetLastUpdated() page := mustache.RenderFileInLayout(top, layout, data) fmt.Fprint(w, page) }
func showBackupDate(store configstore.Store, w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) t, err := time.Parse(file.DefaultDateFormat, vars["date"]) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } datesStore, err := store.Dates(vars["hostname"]) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } // Find the backup on or after the specified date var idx int for i, date := range datesStore { if t.Before(date) { idx = i - 1 } } if idx == -1 { idx = 0 } e := configstore.Entry{ Name: vars["hostname"], Date: datesStore[idx], } err = store.Get(&e) if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } em := struct { Hostname string Date string Content string }{ vars["hostname"], datesStore[idx].String(), e.Content.String(), } io.WriteString(w, mustache.RenderFileInLayout("templates/entry.html.mustache", "templates/layout.html.mustache", em)) }
func renderStream() string { items := []*StreamItem{ dummyStreamItem(), dummyStreamItem(), dummyStreamItem()} str := new(Stream) str.Items = make([]*StreamItem, len(items)) for i, v := range items { str.Items[i] = compileStreamItem(v) } html := mustache.RenderFileInLayout("Pages/Stream.mustache", "Pages/layout.mustache", str) return html }
func AboutHandler(w http.ResponseWriter, r *http.Request) { dir := path.Join(os.Getenv("PWD"), "templates") aboutPage := path.Join(dir, "about.html") layout := path.Join(dir, "pageLayout.html") db := DB{appengine.NewContext(r)} totalUsers, _ := db.GetTotalUsers() stats := map[string]interface{}{"users": totalUsers} stats["lastUpdated"] = db.GetLastUpdated() data := mustache.RenderFileInLayout(aboutPage, layout, stats) fmt.Fprint(w, data) }
// IndexHandler writes out templates func IndexHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) { username, userID := GetUserData(cs, req) context := map[string]interface{}{ "title": "Magnet", "csrf_token": nosurf.Token(req), "bookmarks": GetBookmarks(0, connection, userID), "tags": GetTags(connection, userID), "username": username, } context["load_more"] = len(context["bookmarks"].([]Bookmark)) == 50 w.Write([]byte(mustache.RenderFileInLayout("templates/home.mustache", "templates/base.mustache", context))) }
/* * Handles rendering templates in a normalized context */ func RenderTemplate(template string, context map[string]interface{}) string { title, _ := Config.GetString("general", "title") motto, _ := Config.GetString("general", "motto") var send = map[string]interface{}{ "blog_title": title, "blog_motto": motto, } // Append all values of context to the global context for key, val := range context { send[key] = val } return mustache.RenderFileInLayout("templates/"+template, "templates/base.mustache", send) }
func indexHandler(s Services, w http.ResponseWriter, r *http.Request) { args := map[string]string{ "homepage": "yes", } user, _ := getUser(s, w, r) if user != nil { args["username"] = user.screenName } data := mustache.RenderFileInLayout( "/usr/share/tweetautofeeder/templates/main_page.must", "/usr/share/tweetautofeeder/templates/layout.must", args) w.Write([]byte(data)) return }
func SearchHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) dir := path.Join(os.Getenv("PWD"), "templates") search := path.Join(dir, "search.html") layout := path.Join(dir, "pageLayout.html") data := map[string]interface{}{ "query": r.FormValue("q"), "count": 0, } if len(r.FormValue("q")) > 0 { results, err := SearchUsers(c, r.FormValue("q")) if err != nil { c.Errorf("got err on search: %v", err) } switch r.FormValue("s") { case "overall": sort.Sort(ByOverall(results)) break case "followers": sort.Sort(ByFollowers(results)) break case "loops": sort.Sort(ByLoops(results)) break case "posts": sort.Sort(ByPosts(results)) break case "revines": sort.Sort(ByRevines(results)) break } if r.Method == "GET" { data["count"] = len(results) data["results"] = results } else if r.Method == "POST" { jsonData, _ := json.Marshal(results) fmt.Fprint(w, string(jsonData)) return } } page := mustache.RenderFileInLayout(search, layout, data) fmt.Fprint(w, page) }
func ExportHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) db := DB{c} vars := mux.Vars(r) if r.Method == "GET" { StartupHandler(w, r) userId, err := strconv.ParseInt(vars["user"], 10, 64) if err != nil { c.Errorf("got err: %v", err) http.Redirect(w, r, "/404", 301) return } userMeta, err := db.GetUserMeta(userId) if err == datastore.ErrNoSuchEntity { http.Redirect(w, r, "/404", 301) return } user := userMeta.(StoredUserMeta) data := map[string]string{"username": user.Username, "userId": vars["user"], "captcha": Config["captchaPublic"]} dir := path.Join(os.Getenv("PWD"), "templates") export := path.Join(dir, "export.html") layout := path.Join(dir, "pageLayout.html") page := mustache.RenderFileInLayout(export, layout, data) fmt.Fprint(w, page) } else if r.Method == "POST" { client := urlfetch.Client(c) url := "https://www.google.com/recaptcha/api/siteverify?secret=" + Config["captchaPrivate"] url += "&response=" + r.FormValue("g-recaptcha-response") + "&remoteip=" + r.RemoteAddr req, _ := http.NewRequest("GET", url, nil) resp, err := client.Do(req) if err != nil { c.Errorf("got err: %v", err) return } body, _ := ioutil.ReadAll(resp.Body) var data map[string]interface{} json.Unmarshal(body, &data) if data["success"].(bool) { export := Export{c} export.User(vars["user"], w) } else { fmt.Fprint(w, "Seems like your CAPTCHA was wrong. Please press back and try again.") } } }
func main() { fmt.Println("### Welcome to the Blue Mandarin Lab Flash Card Server ###") err := zhDicts.LoadDb() if err != nil { panic(err) } defer zhDicts.CloseDb() err = cedict.Initialize() if err != nil { panic(err) } err = moedict.Initialize() if err != nil { panic(err) } findWordsInSentencesRegexp, err = regexp.Compile("\\[(.*?)\\]") if err != nil { panic(err) } findCharInMcdsRegexp, err = regexp.Compile(clozeBegin + "(.*?)" + clozeEnd) if err != nil { panic(err) } // Load html files, the array at the end contains the js files to be loaded homeHtml := mustache.RenderFileInLayout("home.html", layoutFile, map[string]interface{}{}) vocabHtml := mustache.RenderFileInLayout("vocab.html", layoutFile, map[string]interface{}{"jsfiles": []string{"vocab"}}) moeVocabHtml := mustache.RenderFileInLayout("moe-vocab.html", layoutFile, map[string]interface{}{"jsfiles": []string{"moe-vocab"}}) sentencesHtml := mustache.RenderFileInLayout("sentences.html", layoutFile, map[string]interface{}{"jsfiles": []string{"sentences"}}) mcdsHtml := mustache.RenderFileInLayout("mcds.html", layoutFile, map[string]interface{}{"jsfiles": []string{"mcds", "mcds-dict"}}) pinyinifyHtml := mustache.RenderFileInLayout("pinyinify.html", layoutFile, map[string]interface{}{"jsfiles": []string{"pinyinify"}}) settingsHtml := mustache.RenderFileInLayout("settings.html", layoutFile, map[string]interface{}{"jsfiles": []string{"settings"}}) // FIXME set active class in navbar // Set up the http server // small helper function (used below) addStaticHtmlHandler := func(path string, html string) { http.HandleFunc(path, func(writer http.ResponseWriter, request *http.Request) { fmt.Fprintf(writer, html) }) } addStaticHtmlHandler(homePath, homeHtml) addStaticHtmlHandler(vocabPath, vocabHtml) addStaticHtmlHandler(moeVocabPath, moeVocabHtml) addStaticHtmlHandler(sentencesPath, sentencesHtml) addStaticHtmlHandler(mcdsPath, mcdsHtml) addStaticHtmlHandler(pinyinifyPath, pinyinifyHtml) addStaticHtmlHandler(settingsPath, settingsHtml) http.HandleFunc(vocabLookupPath, vocabLookupHandler) http.HandleFunc(moeVocabLookupPath, moeVocabLookupHandler) http.HandleFunc(sentencesLookupPath, sentencesLookupHandler) http.HandleFunc(mcdsLookupPath, mcdsLookupHandler) http.HandleFunc(pinyinifyLookupPath, pinyinifyLookupHandler) // assets file server http.Handle(assetsPath, http.FileServer(http.Dir("."))) http.ListenAndServe(":8080", nil) }
func apiDoc(w http.ResponseWriter, req *http.Request) { io.WriteString(w, mustache.RenderFileInLayout("templates/api.html.mustache", "templates/layout.html.mustache", nil)) }
// Renders with a layout template. // // Layout should have {{content}} variable func RenderInLayout(txn *Txn, path, layoutPath string, context map[string]interface{}) { viewsPath := txn.ServerConfig.MustString("http.html.view_directory", "") layPath := fmt.Sprintf("%s%s", viewsPath, layoutPath) templatePath := fmt.Sprintf("%s%s", viewsPath, path) writeResponse(txn, "text/html", mustache.RenderFileInLayout(templatePath, layPath, contxt(txn, context))) }
func dashboard(store configstore.Store, w http.ResponseWriter, req *http.Request) { names, err := store.Names() if err != nil { log.Printf("Error: %s", err) http.Error(w, "error :(", 500) return } if req.Header.Get("Accept") == "application/json" { w.Header().Set("Content-type", "application/json") var data = []interface{}{} for _, name := range names { dates, err := store.Dates(name) if err != nil { continue } var date *time.Time if len(dates) > 0 { date = &dates[0] } else { date = nil } data = append(data, struct { Hostname string LastBackup *time.Time `json:",omitempty"` }{ Hostname: name, LastBackup: date, }) } enc := json.NewEncoder(w) err = enc.Encode(data) } else { var data = struct { Entries []struct { Hostname string LastBackup *time.Time Ago string AgoStatus string } }{} for _, name := range names { dates, err := store.Dates(name) if err != nil { continue } var date *time.Time if len(dates) > 0 { date = &dates[0] } else { date = nil } data.Entries = append(data.Entries, struct { Hostname string LastBackup *time.Time Ago string AgoStatus string }{ Hostname: name, LastBackup: date, Ago: dashboardAgo(date, 24, 72), AgoStatus: dashboardAgoStatus(date, 24, 72), }) } io.WriteString(w, mustache.RenderFileInLayout("templates/dashboard.html.mustache", "templates/layout.html.mustache", data)) } }
func renderSplash() string { html := mustache.RenderFileInLayout("Pages/Splash.mustache", "Pages/layout.mustache") return html }
// TestHandler runs the tests func TestHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) { w.Write([]byte(mustache.RenderFileInLayout("templates/test.mustache", "templates/test.base.mustache", nil))) }
/** * Takes a template name and context and renders using the layout defined below */ func renderHTML(template string, context map[string]string) string { layoutPath := "templates/layout.mustache" templatePath := "templates/" + template + ".mustache" return mustache.RenderFileInLayout(templatePath, layoutPath, context) }