small pixel drawing of a pufferfish existentialcrisis.sh

main.go

package main

import (
	"html/template"
	"path/filepath"
	"net/http"
	"log"
	"os"
	"fmt"
	"git.j3s.sh/existentialcrisis.sh/quote"
)

func main() {
	http.HandleFunc("/", serveTemplate)
	http.HandleFunc("/api/v1/crisis/quote", quoteHandler)
	http.HandleFunc("/api/v1/crisis/life", lifeHandler)

	log.Println("listening on :4357 tbh")
	err := http.ListenAndServe(":4357", nil)
	if err != nil {
		log.Fatal(err)
	}
}

func serveTemplate(w http.ResponseWriter, r *http.Request) {
	lp := filepath.Join("templates", "layout.html")
	if r.URL.Path == "/" {
		r.URL.Path = "index.html"
	}
	fp := filepath.Join("templates", filepath.Clean(r.URL.Path))
	log.Println(r.URL.Path)

	info, err := os.Stat(fp)
	if err != nil {
		if os.IsNotExist(err) {
			http.NotFound(w, r)
			return
		}
	}

	if info.IsDir() {
		http.NotFound(w, r)
		return
	}

	tmpl, err := template.ParseFiles(lp, fp)
	if err != nil {
		log.Println(err.Error())
		http.Error(w, http.StatusText(500), 500)
		return
	}

	err = tmpl.ExecuteTemplate(w, "layout", nil)
	if err != nil {
		log.Println(err.Error())
		http.Error(w, http.StatusText(500), 500)
	}
}

func quoteHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	randomQuote := quote.GetRandomQuote()
	fmt.Fprintf(w, randomQuote)
}

func lifeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	// hardcoded for now
	age := 29
	yearsTilDeath := 77 - age
	weeksToLive := yearsTilDeath * 52
	text := "weeks of your life:\n"
	weeksOfLifeOnAverage := 4004
	weekOfLifeYouAreOn := weeksOfLifeOnAverage - weeksToLive

	for i := 0; i < weeksOfLifeOnAverage; i++ {
		if i % 50 == 0 {
			text = text + "*\n"
		} else if i == weekOfLifeYouAreOn {
			text = text + "\n[*] you are here\n"
			log.Println(i)
		} else {
			text = text + "*"
		}
	}

	fmt.Fprintf(w, text)
}