Beispiel #1
0
func show(w http.ResponseWriter, r *http.Request) {
	coinflipKey := strings.Split(r.URL.Path, "/")[2]
	coinflip, _ := database.FindCoinflip(coinflipKey)

	participants := coinflip.FindParticipants()

	email_list := participantsMap(participants, func(p database.Participant) map[string]string {
		var seen_at string
		if p.Seen.Time.IsZero() {
			seen_at = "hasn't registered yet"
		} else {
			seen_at = p.Seen.Time.Format("Monday 2 January 2006")
		}
		return map[string]string{"email": p.Email, "seen_at": seen_at}
	})

	var result string
	if coinflip.Result.String == "" {
		result = "Nothing yet! Not everybody checked in. Perhaps a little encouragement?"
	} else {
		result = coinflip.Result.String
	}

	str_to_str := map[string]string{"count": fmt.Sprint(len(email_list)), "head": coinflip.Head, "tail": coinflip.Tail, "result": result}
	str_to_slice := map[string][]map[string]string{"participants": email_list}
	fmt.Fprint(w, mustache.RenderFile("./views/layout.html", map[string]string{"body": mustache.RenderFile("./views/show.html", str_to_str, str_to_slice)}))
}
Beispiel #2
0
func parseTemplate(filename string, data *Container) (string, error) {
	fileLocation := fmt.Sprintf("%s/%s.mustache", utils.GetOriginFolder(), filename)
	if utils.Exists(fileLocation) {
		log.Debugf("  + Parsing %s template", fileLocation)
		before := fmt.Sprintf("%s/%s/%s/%s.before.mustache", utils.GetOriginFolder(), data.Config["client"], data.Config["enviroment"], filename)
		after := fmt.Sprintf("%s/%s/%s/%s.after.mustache", utils.GetOriginFolder(), data.Config["client"], data.Config["enviroment"], filename)

		if utils.Exists(before) {
			log.Debugf("    + Parsing %s:before template", before)
			data.SubTemplate.Before = mustache.RenderFile(before, data)
		} else {
			log.Debugf("    + Not Parsing %s:before template", before)
		}

		if utils.Exists(after) {
			log.Debugf("      + Parsing %s:after template", after)
			data.SubTemplate.After = mustache.RenderFile(after, data)
		} else {
			log.Debugf("    + Not Parsing %s:after template", after)
		}

		parsedData := mustache.RenderFile(fileLocation, data)
		return parsedData, nil
	}
	return "", errors.New(fmt.Sprintf("Can not find %s", fileLocation))
}
Beispiel #3
0
func std_layout(blog_config map[string]interface{}, f func(w http.ResponseWriter, req *http.Request)) func(w http.ResponseWriter, req *http.Request) {

	p := func(w http.ResponseWriter, req *http.Request) {
		appcontext := appengine.NewContext(req)
		myurl, err := realhostname(req, appcontext)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		scheme := "http://"
		if req.TLS != nil {
			scheme = "https://"
		}
		context := map[string]interface{}{"app_url": scheme + myurl + config.Stringify(blog_config["blog_root"])}

		bloginfo := config.Stringify_map(config.Merge(blog_config, context))

		start := time.Now()
		template_dir := "templates/"

		h := mustache.RenderFile(template_dir+"header.html.mustache", bloginfo)
		io.WriteString(w, h)

		f(w, req)

		sidebar(w, req, blog_config)

		delta := time.Since(start).Seconds()

		timing := map[string]interface{}{"timing": fmt.Sprintf("%0.2fs", delta)}
		if delta > 0.100 {
			timing["slow_code"] = "true"
		}

		u := user.Current(appcontext)
		if u != nil {
			logout, err := user.LogoutURL(appcontext, "/")
			if err != nil {
				http.Error(w, "error generating logout URL!", http.StatusInternalServerError)
				appcontext.Errorf("user.LogoutURL: %v", err)
				return
			}
			timing["me"] = fmt.Sprintf("%s", u)
			timing["logout"] = logout
		}

		bloginfo = config.Stringify_map(config.Merge(blog_config, timing))
		f := mustache.RenderFile(template_dir+"footer.html.mustache", bloginfo)
		io.WriteString(w, f)
	}

	return p
}
Beispiel #4
0
func home(w http.ResponseWriter, r *http.Request) {
	/* static file serve */
	if len(r.URL.Path) != 1 {
		http.ServeFile(w, r, "./views"+r.URL.Path)
		return
	}

	/* the real root */
	count := database.TotalNumberOfParticipants()

	/*long, very long line */
	fmt.Fprint(w, mustache.RenderFile("./views/layout.html", map[string]string{"body": mustache.RenderFile("./views/home.html", map[string]string{"title": "Awesome coin tosses - Coinflips.net", "nr_of_flips": fmt.Sprint(count)})}))
}
Beispiel #5
0
func adminGet(ctx *web.Context) string {
	if !checkGodLevel(ctx) {
		return mustache.RenderFile("templ/admin_login.mustache")
	}
	Db := DBGet()
	defer Db.Close()

	posts, _ := Db.GetLastNPosts(256)
	x := map[interface{}]interface{}{
		"Posts": posts,
	}

	return mustache.RenderFile("templ/admin_post.mustache", &x)
}
Beispiel #6
0
func GetSitemap(blog_config map[string]interface{}) func(w http.ResponseWriter, req *http.Request) {
	template_dir := "templates/"
	l := func(w http.ResponseWriter, req *http.Request) {
		appcontext := appengine.NewContext(req)

		myurl, err := realhostname(req, appcontext)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		scheme := "http://"
		if req.TLS != nil {
			scheme = "https://"
		}

		urlprefix := scheme + myurl + config.Stringify(blog_config["blog_root"])

		postchan := make(chan post.Post, 16)
		errchan := make(chan error)
		go post.ExecuteQuery(appcontext, post.GetAllPosts(), -1, -1, post.NullFilter, postchan, errchan)

		entries := bytes.NewBufferString("")

		me_context := map[string]interface{}{"url": urlprefix,
			"lastmod_date": post.GetLatestDate(appcontext).Format("2006-01-02")}
		me_total_con := config.Stringify_map(config.Merge(blog_config, me_context))
		me_c := mustache.RenderFile(template_dir+"sitemap_entry.mustache", me_total_con)
		io.WriteString(entries, me_c)
		for p := range postchan {
			context := map[string]interface{}{"url": urlprefix + "article/" + p.StickyUrl,
				"lastmod_date": p.Postdate.Format("2006-01-02")}
			total_con := config.Stringify_map(config.Merge(blog_config, context))
			c := mustache.RenderFile(template_dir+"sitemap_entry.mustache", total_con)
			io.WriteString(entries, c)
		}

		err, ok := <-errchan
		if ok {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		context := map[string]interface{}{"content": entries}
		total_con := config.Stringify_map(config.Merge(blog_config, context))
		c := mustache.RenderFile(template_dir+"sitemap.mustache", total_con)
		io.WriteString(w, c)
	}
	return l
}
Beispiel #7
0
func CacheHandler(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	switch r.Method {
	case "GET":
		params := r.URL.Query()
		page, err := strconv.Atoi(params.Get("page"))
		if err != nil {
			page = 1
		}

		subcat := params.Get("subcat")

		responseContent := search.CacheSearch(subcat, page)
		var responseBody []byte
		if strings.Contains(r.Header["Accept"][0], "application/json") {
			responseBody, err = json.Marshal(responseContent)
			if err != nil {
				internalServerError(w, &r.Request)
				return
			}
		} else {
			responseBody = []byte(mustache.RenderFile("view/cache.html", responseContent))
		}
		w.Write(responseBody)
	default:
		methodNotAllowed(w, &r.Request)
	}
}
Beispiel #8
0
func compileStream(s *Stream) *Stream {
	for _, v := range s.Items {
		compileStreamItem(v)
	}
	s.Html = mustache.RenderFile("Pages/Stream.mustache", s)
	return s
}
Beispiel #9
0
func AdminHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	db := DB{c}
	adminUser := user.Current(c)
	if adminUser == nil {
		url, _ := user.LoginURL(c, "/admin/dashboard")
		http.Redirect(w, r, url, 301)
		return
	}
	if r.Method == "GET" {
		dir := path.Join(os.Getenv("PWD"), "templates")
		admin := path.Join(dir, "admin.html")
		data := map[string]interface{}{"user": adminUser.String(), "config": Config}
		page := mustache.RenderFile(admin, data)
		fmt.Fprint(w, page)
	} else if r.Method == "POST" {
		if len(r.FormValue("v")) == 0 {
			return
		}
		switch r.FormValue("op") {
		case "UnqueueUser":
			db.Context.Infof("unqueuing %v", r.FormValue("v"))
			db.UnqueueUser(r.FormValue("v"))
		case "BatchUsers":
			users := strings.Split(r.FormValue("v"), ",")
			for _, v := range users {
				QueueUser(v, c)
			}
		}
		fmt.Fprintf(w, "{\"op\":\"%v\",\"success\":true}", r.FormValue("op"))
	}
}
Beispiel #10
0
func permalink(w http.ResponseWriter, r *http.Request) {
	idstr := r.URL.Path[len("/post/"):]
	post, err := PostBySlug(idstr)
	if err != nil {
		http.Error(w, fmt.Sprintf("invalid post %s: %s", idstr, err.Error()), http.StatusBadRequest)
		return
	}

	if r.Method == "DELETE" {
		if !IsAuthed(w, r) {
			return
		}

		post.MarkDeleted()

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusNoContent)
		w.Write([]byte("{\"ok\":true}"))
		return
	}

	owner := AccountForOwner()
	data := map[string]interface{}{
		"post":      post,
		"OwnerName": owner.DisplayName,
	}
	html := mustache.RenderFile("html/permalink.html", data)
	w.Write([]byte(html))
}
Beispiel #11
0
func Render(ctx *web.Context, tmpl string, config *Config, name string, data interface{}) {
	tmpl = filepath.Join(config.Get("datadir"), tmpl)
	ctx.WriteString(mustache.RenderFile(tmpl,
		map[string]interface{}{
			"config": config,
			name:     data}))
}
Beispiel #12
0
func entrybar(blog_config map[string]interface{}, w http.ResponseWriter, req *http.Request) {
	template_dir := "templates/"
	appcontext := appengine.NewContext(req)
	myurl, err := realhostname(req, appcontext)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	scheme := "http://"
	if req.TLS != nil {
		scheme = "https://"
	}

	urlprefix := scheme + myurl + config.Stringify(blog_config["blog_root"])

	postchan := make(chan post.Post, 16)
	errchan := make(chan error)
	go post.ExecuteQuery(appcontext, post.GetAllPosts(), -1, -1, func(post.Post) bool { return true }, postchan, errchan)

	for p := range postchan {
		context := map[string]interface{}{"url": urlprefix + "article/" + p.StickyUrl,
			"lastmod_date": p.Postdate.Format("2006-01-02")}
		total_con := config.Stringify_map(config.Merge(blog_config, context))
		c := mustache.RenderFile(template_dir+"edit_entrybar.html.mustache", total_con)
		io.WriteString(w, c)
	}

	err, ok := <-errchan
	if ok {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Beispiel #13
0
func (i *IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	data := map[string]string{}
	path := filepath.Join(i.templates, "index.mustache")
	html := mustache.RenderFile(path, data)
	buff := bytes.NewReader([]byte(html))
	http.ServeContent(w, r, "index.html", i.updated, buff)
	log.Printf("Request: %v", r.RequestURI)
}
func (m *BaseMail) BuildMessage(subject string, template string, data interface{}) []byte {
	//mime := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"

	// load the template
	body := mustache.RenderFile(template, data)

	msg := []byte(body)
	return msg
}
Beispiel #15
0
func editGet(ctx *web.Context) string {
	if !checkGodLevel(ctx) {
		return mustache.RenderFile("templ/admin_login.mustache")
	}
	Db := DBGet()
	defer Db.Close()

	id, _ := strconv.ParseInt(ctx.Params["id"], 10, 64)
	post, err := Db.GetPost(id)
	if err != nil {
		return "couldn't load post with given id!"
	}
	posts, _ := Db.GetLastNPosts(256)
	x := map[interface{}]interface{}{
		"Posts": posts,
	}

	return mustache.RenderFile("templ/admin_edit.mustache", &post, &x)
}
Beispiel #16
0
func home() string {
	c := Content{
		"Hello",
		"My name is abhi",
	}
	return mustache.RenderFile(
		"template/layout.html",
		map[string]string{
			"title": c.Title, "content": c.Content,
		},
		nil,
	)
}
Beispiel #17
0
func compileFiles(fullPath string, f os.FileInfo, err error) error {
	if !f.IsDir() {
		newPath := mustache.Render(fullPath, templateConfig.Variables)
		rendered := mustache.RenderFile(fullPath, templateConfig.Variables)

		os.Remove(fullPath)
		ioutil.WriteFile(newPath, []byte(rendered), f.Mode())

		printCreating(newPath)
	}

	return nil
}
Beispiel #18
0
func (ac *ActionsConfig) Preview(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

	username := ps.ByName("username")
	chopid := ps.ByName("chopid")
	s := chopper.NewSlapchop(ac.Host, username, chopid)
	t_files, _ := s.LoadFiles(ac.UploadDir)
	tiles := s.LoadTiles(ac.HostName, t_files)
	grid := s.Grid(tiles)

	html := mustache.RenderFile(ac.TemplatePath, grid)

	w.WriteHeader(http.StatusOK)
	w.Write([]byte(html))
}
Beispiel #19
0
func sidebar(w http.ResponseWriter, req *http.Request, blog_config map[string]interface{}) {
	template_dir := "templates/"

	sidebar_links := bytes.NewBufferString("")

	context := map[string]interface{}{"label_link": "http://qrunk.com",
		"label_title": "qrunk.com"}
	total_con := config.Stringify_map(config.Merge(blog_config, context))
	c := mustache.RenderFile(template_dir+"sidebar_entry.html.mustache", total_con)
	io.WriteString(sidebar_links, c)

	sidebar_topics := bytes.NewBufferString("")

	appcontext := appengine.NewContext(req)
	tags, counts, err := post.GetAllTags(appcontext)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	for i := range tags {
		n, count := tags[i], counts[i]
		context = map[string]interface{}{"label_link": "/label/" + n,
			"label_title": n,
			"label_count": fmt.Sprintf("%v", count)}
		total_con = config.Stringify_map(config.Merge(blog_config, context))
		c = mustache.RenderFile(template_dir+"sidebar_entry.html.mustache", total_con)
		io.WriteString(sidebar_topics, c)
	}

	context = map[string]interface{}{"sidebar_links": string(sidebar_links.Bytes()),
		"sidebar_topics": string(sidebar_topics.Bytes())}
	total_con = config.Stringify_map(config.Merge(blog_config, context))
	c = mustache.RenderFile(template_dir+"sidebar.html.mustache", total_con)
	io.WriteString(w, c)
}
Beispiel #20
0
func main() {
	raw, err := ioutil.ReadFile("json-generator.json")
	if err != nil {
		log.Fatal("opening json", err.Error())
	}

	var users []User
	json.Unmarshal([]byte(raw), &users)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		content := mustache.RenderFile("application.mustache", users)
		fmt.Fprintf(w, "<!DOCTYPE html><html><head></head><body><div id='react'>%s</div><script>window.INITIAL_DATA = %s;</script></body></html>", content, raw)
	})

	log.Fatal(http.ListenAndServe(":3000", nil))
}
Beispiel #21
0
func wp_core_config(options *CoreConfigOptions) {
	var err error

	config_path := fmt.Sprintf("%s/wp-config.php", options.Path)

	if fileExists(config_path) && !options.Force {
		fmt.Println("Config file already exists")
		os.Exit(1)
	}

	/* Get keys and salts from wp api */
	salts := getUrlContents(WP_SALTS_API)
	if len(salts) == 0 {
		fmt.Println("Unable to get salts from wordpress API")
		os.Exit(1)
	}

	/* Check database connection */
	checkDbConnection(options)

	/* Setup config for rendering */
	config := map[string]string{
		"dbname":         options.DbName,
		"dbuser":         options.DbUser,
		"dbpass":         options.DbPass,
		"dbhost":         options.DbHost,
		"dbcharset":      options.DbCharset,
		"dbcollate":      options.DbCollate,
		"dbprefix":       options.DbPrefix,
		"keys-and-salts": salts,
	}

	/* Remove existing config file */
	run(fmt.Sprintf("rm -f %s", config_path))

	result := mustache.RenderFile(options.Template, config)
	err = ioutil.WriteFile(config_path, []byte(result), 0644)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	/* Print result */
	fmt.Printf("New config file generated at %s\n", config_path)
}
Beispiel #22
0
func index(w http.ResponseWriter, r *http.Request) {
	posts, err := RecentPosts(20)
	if err != nil {
		logr.Errln("Error loading recent posts for home page:", err.Error())
	}

	owner := AccountForOwner()
	data := map[string]interface{}{
		"posts":     posts,
		"OwnerName": owner.DisplayName,
	}
	if len(posts) > 0 {
		data["LastPost"] = posts[len(posts)-1]
	}
	html := mustache.RenderFile("html/index.html", data)
	w.Write([]byte(html))
}
Beispiel #23
0
func populateDir(dir string, template string, context map[string]string) {
	tpldir := path.Join(config.GetRepoPath(), template)
	files, err := getDirContents(tpldir)
	if err != nil {
		log.Fatalf("Could not get contents of template %s: %s", template, err)
	}
	for index := 0; index < len(files); index++ {
		fn := files[index]
		content := mustache.RenderFile(path.Join(tpldir, fn), context)
		f, err := os.Create(path.Join(dir, fn))
		if err != nil {
			log.Fatalf("Could not create %s: %s", fn, err)
		}
		f.WriteString(content)
		f.Close()
	}
}
Beispiel #24
0
func UploadHandler(req *http.Request) Response {
	var context = map[string]interface{}{}
	str := mustache.RenderFile("templates/hello.html", context)
	if req.Method == "POST" {
		file, _, e := req.FormFile("file")
		if e != nil {
			fmt.Printf("Error:%s\n", e)
			return ResponseBadRequest("file parameter missing")
		}
		buf := new(bytes.Buffer)
		buf.ReadFrom(file)
		e = ioutil.WriteFile("test.jpg", buf.Bytes(), 0660)
		if e != nil {
			fmt.Printf("Error writing:%s\n", e)
			return ResponseServerError("Unable to save file")
		}
		return ResponseRedirect("/hello")
	}
	return ResponseOK(str)
}
Beispiel #25
0
func WriteRssForPosts(w http.ResponseWriter, r *http.Request, posts []*Post, titleFormat string) (err error) {
	var host string
	var port string
	if strings.Contains(r.Host, ":") {
		host, port, err = net.SplitHostPort(r.Host)
		if err != nil {
			return
		}
	} else {
		host = r.Host
		// TODO: set port appropriately if we're on HTTPS
		port = "80"
	}

	owner := AccountForOwner()
	firstPost, err := FirstPost()
	if err != nil {
		return
	}

	// TODO: somehow determine if we're on HTTPS or no?
	baseurlUrl := url.URL{"http", "", nil, r.Host, "/", "", ""}
	baseurl := strings.TrimRight(baseurlUrl.String(), "/")

	data := map[string]interface{}{
		"posts":     posts,
		"OwnerName": owner.DisplayName,
		"Title":     fmt.Sprintf(titleFormat, owner.DisplayName),
		"baseurl":   baseurl,
		"host":      host,
		"port":      port,
		"FirstPost": firstPost,
	}
	logr.Debugln("Rendering RSS with baseurl of", baseurl)
	xml := mustache.RenderFile("html/rss.xml", data)
	w.Header().Set("Content-Type", "application/rss+xml")
	w.Write([]byte(xml))
	return
}
Beispiel #26
0
func AtomForPosts(r *http.Request, posts []*Post, titleFormat string) string {
	// TODO: somehow determine if we're on HTTPS or no?
	baseurlUrl := url.URL{"http", "", nil, r.Host, "/", "", ""}
	baseurl := strings.TrimRight(baseurlUrl.String(), "/")

	var lastPost *Post = nil
	if len(posts) > 0 {
		lastPost = posts[0]
	}

	owner := AccountForOwner()
	data := map[string]interface{}{
		"Posts":     posts,
		"OwnerName": owner.DisplayName,
		"Title":     fmt.Sprintf(titleFormat, owner.DisplayName),
		"baseurl":   baseurl,
		"LastPost":  lastPost,
	}
	logr.Debugln("Rendering Atom with baseurl of", baseurl)
	xml := mustache.RenderFile("html/atom.xml", data)
	return xml
}
Beispiel #27
0
func main() {

	mapped_data = make(map[string]string)

	flag.Parse()

	//Error checking on arguements passed in
	if *template == "{file}" {
		log.Fatal("ERROR: A template file location must be specified with --template={{path to template file}}")
	} else {
		file, err := os.Open(*template)
		if file == nil && err != nil {
			log.Fatalf("ERROR: Unable to open template file '%s'", *template)
		}
	}

	//Split up the data set passed in
	each_set := strings.Split(*data, ":~")

	for i := range each_set {
		split_data := strings.Split(each_set[i], "=")
		if len(split_data) > 1 {
			mapped_data[split_data[0]] = split_data[1]
		}
	}

	file_data := mustache.RenderFile(*template, mapped_data)

	if *output != "{file}" {
		out_file, err := os.Create(*output)
		if err != nil {
			log.Fatalf("ERROR: Unable to create output file %s", *output)
		}
		out_file.WriteString(file_data)
	}
}
Beispiel #28
0
func blogHandler(w http.ResponseWriter, r *http.Request) {
	data := mustache.RenderFile("/usr/share/tweetautofeeder/templates/blog_main.must", map[string]string{"thing": "places"})
	w.Write([]byte(data))
	return
}
Beispiel #29
0
// Top page router
func Top(c web.C, w http.ResponseWriter, r *http.Request) {
	header := w.Header()
	header.Add("Content-Type", "text/html; charset=utf-8")
	view := mustache.RenderFile("views/index.html")
	fmt.Fprintln(w, view)
}
Beispiel #30
0
func index(ctx *web.Context) string {
	return mustache.RenderFile("templates/index.html")
}