all repos — artbound-go @ 856ca092b7af01e9ef7fcfc525473f3e93163d05

The official administration panel for ArtBound, by EarthBound Café.

artbound.go (view raw)

  1package main
  2
  3import (
  4	"bytes"
  5	"html/template"
  6	"log"
  7	"net/http"
  8	"os"
  9	"time"
 10
 11	"github.com/joho/godotenv"
 12)
 13
 14var templatesDirectory = "templates/"
 15var indexTemplate = template.Must(template.ParseFiles(templatesDirectory + "index.html"))
 16var helpTemplate = template.Must(template.ParseFiles(templatesDirectory + "help.html"))
 17
 18type TemplateData struct {
 19	Emoji        EmojiDict
 20	LastUpdated  string
 21	CurrentMonth string
 22}
 23
 24func indexHandler(w http.ResponseWriter, r *http.Request) {
 25	switch method := r.Method; method {
 26	case http.MethodGet:
 27		// render template
 28		lastUpdated := "last updated"
 29		currentMonth := time.Now().Format("2006-01")
 30		templateData := &TemplateData{defaultEmojis, lastUpdated, currentMonth}
 31		buf := &bytes.Buffer{}
 32		err := indexTemplate.Execute(buf, templateData)
 33		if err != nil {
 34			http.Error(w, err.Error(), http.StatusInternalServerError)
 35			return
 36		}
 37		buf.WriteTo(w)
 38	case http.MethodPost:
 39		// render json
 40		contentType := r.Header.Get("Content-Type")
 41		err := r.ParseForm()
 42		if err != nil {
 43			log.Fatal("Could not parse form.")
 44			http.Error(w, err.Error(), http.StatusInternalServerError)
 45			return
 46		}
 47		log.Println(contentType, r.Form.Get("month"))
 48		http.Error(w, "WIP.", http.StatusMethodNotAllowed)
 49		return
 50	default:
 51		http.Error(w, "Please use GET or POST.", http.StatusMethodNotAllowed)
 52		return
 53	}
 54}
 55
 56func helpHandler(w http.ResponseWriter, r *http.Request) {
 57	if r.Method != http.MethodGet {
 58		http.Error(w, "Please use GET.", http.StatusMethodNotAllowed)
 59		return
 60	}
 61
 62	buf := &bytes.Buffer{}
 63	err := helpTemplate.Execute(buf, defaultEmojis)
 64	if err != nil {
 65		http.Error(w, err.Error(), http.StatusInternalServerError)
 66		return
 67	}
 68	buf.WriteTo(w)
 69}
 70
 71func clearHandler(w http.ResponseWriter, r *http.Request) {
 72	if r.Method != http.MethodPost {
 73		http.Error(w, "Please use POST.", http.StatusMethodNotAllowed)
 74		return
 75	}
 76
 77	// TODO: actually clear cache
 78	http.Error(w, "Done.", http.StatusOK)
 79}
 80
 81func main() {
 82	err := godotenv.Load()
 83	if err != nil {
 84		log.Println("No .env file provided.")
 85	}
 86
 87	port := os.Getenv("PORT")
 88	if port == "" {
 89		port = "3000"
 90	}
 91
 92	fs := http.FileServer(http.Dir("./static"))
 93
 94	r := http.NewServeMux()
 95	r.HandleFunc("/", indexHandler)
 96	r.HandleFunc("/help", helpHandler)
 97	r.HandleFunc("/clear", clearHandler)
 98	r.Handle("/static/", http.StripPrefix("/static/", fs))
 99
100	log.Println("Serving on port", port)
101	err = http.ListenAndServe(":"+port, r)
102	if err != nil {
103		log.Fatal(err)
104	}
105}