small pixel drawing of a pufferfish poop.is

main.go

package main

import (
	"html/template"
	"log"
	"net/http"
	"path/filepath"
	"strings"

	"j3s.sh/poop.is/word"
)

var globalURLMap = make(map[string]string)

func main() {
	// pass everything through a muxer because
	// we need to differentiate index from everything
	// else
	http.HandleFunc("/", muxHandler)

	words := word.GetWordList()
	adjective := words.RandomAdjective()

	for {
		if inUse(adjective) {
			adjective = words.RandomAdjective()
			// TODO: handle running out of words -.-
		} else {
			break
		}
	}

	log.Println(adjective)

	log.Println("listening on :8008 tbh")
	err := http.ListenAndServe(":8008", nil)
	if err != nil {
		log.Fatal(err)
	}
	// url := makeURL(adjective)
}

func muxHandler(w http.ResponseWriter, r *http.Request) {
	if len(r.URL.Path) == 1 {
		indexHandler(w, r)
	} else {
		redirectHandler(w, r)
	}
}

func redirectHandler(w http.ResponseWriter, r *http.Request) {
	path := strings.TrimPrefix(r.URL.Path, "/")
	if globalURLMap[path] != "" {
		log.Printf("%s", "found")
		http.Redirect(w, r, globalURLMap[path], 302)
	} else {
		log.Printf("%s", "not found")
		http.Redirect(w, r, "/", 302)
	}
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	tfile := filepath.Join("templates", "index.html")
	tmpl, err := template.ParseFiles(tfile)
	if err != nil {
		log.Println(err.Error())
		http.Error(w, http.StatusText(500), 500)
		return
	}

	if r.Method != http.MethodPost {
		tmpl.Execute(w, nil)
		return
	}

	url := r.FormValue("url")
	// validate the string?

	shortenedURL := shortenURL(url)

	tmpl.Execute(w, shortenedURL)
}

func inUse(word string) bool {
	if globalURLMap[word] != "" {
		return true
	}
	return false
}

func shortenURL(url string) string {
	words := word.GetWordList()
	adjective := words.RandomAdjective()

	// TODO: make this loop not go infinite when the wordlist
	// has been fully consumed
	for {
		if len(globalURLMap) > len(words.Adjectives) {
			adjectiveOne := words.RandomAdjective()
			adjectiveTwo := words.RandomAdjective()
			adjective = adjectiveOne + adjectiveTwo
		}
		if inUse(adjective) {
			adjective = words.RandomAdjective()
		} else {
			break
		}
	}

	var thing string
	thing = "https://poop.is/" + adjective

	associate(adjective, url)
	log.Printf("%+v", url)
	return thing
}

func associate(adjective string, url string) {
	log.Printf("%s: %s", adjective, url)
	globalURLMap[adjective] = url
}