~reesmichael1/chantpointer

5d08de29fb71ff93c78454ff9646e708b876be12 — Michael Rees 5 months ago 0ba42d0
Add --no-cache flag for easier development
2 files changed, 44 insertions(+), 5 deletions(-)

M handlers.go
M main.go
M handlers.go => handlers.go +25 -5
@@ 21,8 21,6 @@ var savedName = "chant.json"
// and nicely displays them to the user
type ErrorHandler func(http.ResponseWriter, *http.Request) error

var templates = template.Must(template.ParseFiles("templates/html/index.html", "templates/html/error.html"))

// Page holds the link to the generated PDF, if it exists
type Page struct {
	URL string


@@ 34,10 32,31 @@ type ErrorPage struct {
	Message string
}

func renderTemplate(w http.ResponseWriter, name string, data interface{},
	codes ...int) error {
	status := http.StatusOK
	if len(codes) > 0 {
		status = codes[0]
	}
	if noCache {
		t, err := template.ParseFiles("templates/html/" + name + ".html")
		if err == nil {
			w.WriteHeader(status)
			err = t.Execute(w, data)
		}
		return err
	}
	w.WriteHeader(status)
	return templates.ExecuteTemplate(w, name+".html", data)
}

func (fn ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if err := fn(w, r); err != nil {
		log.Printf("error: %v\n", err)
		templates.ExecuteTemplate(w, "error.html", ErrorPage{err.Error()})
		errorErr := renderTemplate(w, "error", ErrorPage{err.Error()})
		if errorErr != nil {
			http.Error(w, errorErr.Error(), http.StatusInternalServerError)
		}
	}
}



@@ 117,6 136,7 @@ func GenerateHandler(w http.ResponseWriter, r *http.Request) error {
	err = cmd.Run()
	if err != nil {
		log.Printf("pdflatex error: %v", string(buf.Bytes()))
		os.Chdir(startDir)
		return fmt.Errorf("pdflatex error: %v", err)
	}



@@ 169,10 189,10 @@ func IndexHandler(w http.ResponseWriter, r *http.Request) error {
			return err
		}
		saved := LoadSaved(savedFile)
		return templates.ExecuteTemplate(w, "index.html", Page{
		return renderTemplate(w, "index", Page{
			URL:   chantURL,
			Saved: saved,
		})
	}
	return templates.ExecuteTemplate(w, "index.html", Page{})
	return renderTemplate(w, "index", Page{})
}

M main.go => main.go +19 -0
@@ 3,15 3,34 @@ package main
import (
	"flag"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
)

var noCache bool
var templates *template.Template
var templateFiles []string

func main() {
	var port int
	flag.IntVar(&port, "port", 7777, "the port that the server will run on")
	flag.BoolVar(&noCache, "no-cache", false, "if given, don't cache templates")
	flag.Parse()

	if !noCache {
		files, err := ioutil.ReadDir("templates/html")
		if err != nil {
			log.Fatal(err)
		}

		for _, f := range files {
			templateFiles = append(templateFiles, "templates/html/"+f.Name())
		}
		templates = template.Must(template.ParseFiles(templateFiles...))
	}

	static := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix("/static", static))
	http.HandleFunc("/chant/", ChantHandler)