all repos — existentialcrisis.sh @ 62d34276c33f5d0c1d0ea61bf9252a2ff04ba3a2

existential crisis API

main.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
package main

import (
	"html/template"
	"path/filepath"
	"net/http"
	"log"
	"strconv"
	"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")

	ageraw, _ := r.URL.Query()["age"]
	age, err := strconv.Atoi(ageraw[0])
	if err != nil {
		http.Error(w, http.StatusText(500), 500)
		return
	}

	if ! (1 <= age && age <= 100) {
		http.Error(w, http.StatusText(500), 500)
		return
	}

	yearsTilDeath := 77 - age
	weeksToLive := yearsTilDeath * 52
	text := "saturdays of your life:\n\n"
	weeksOfLifeOnAverage := 4004
	weekOfLifeYouAreOn := weeksOfLifeOnAverage - weeksToLive

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

		if age >= 77 {
			text = "any day now"
		}
	}

	fmt.Fprintf(w, text)
}