mirror of
https://codeberg.org/mycelium/emojiquest.git
synced 2024-11-17 14:39:14 +00:00
97 lines
2.1 KiB
Go
97 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"embed"
|
|
"encoding/csv"
|
|
"flag"
|
|
"fmt"
|
|
"html/template"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type EmojiDetails struct {
|
|
Label string
|
|
Url string
|
|
}
|
|
|
|
type Config struct {
|
|
RequestsFile string
|
|
Listen string
|
|
}
|
|
|
|
//go:embed templates
|
|
var indexHTML embed.FS
|
|
var config Config
|
|
|
|
func handleForm(w http.ResponseWriter, r *http.Request) {
|
|
tmpl := template.Must(template.ParseFS(indexHTML, "templates/index.html"))
|
|
|
|
if r.Method != http.MethodPost {
|
|
tmpl.Execute(w, nil)
|
|
return
|
|
}
|
|
|
|
details := EmojiDetails{
|
|
Label: r.FormValue("shortcode"),
|
|
Url: r.FormValue("url"),
|
|
}
|
|
|
|
now := time.Now().UTC().Format(time.RFC3339)
|
|
var username string
|
|
if r.Header.Get("X-Forwarded-Preferred-Username") == "" {
|
|
username = "unknown"
|
|
} else {
|
|
username = r.Header.Get("X-Forwarded-Preferred-Username")
|
|
}
|
|
entry := strings.Join([]string{now, username, details.Label, details.Url}, ",")
|
|
insertEntry(entry)
|
|
|
|
tmpl.Execute(w, struct{ Success bool }{true})
|
|
}
|
|
|
|
func handleRequested(w http.ResponseWriter, r *http.Request) {
|
|
tmpl := template.Must(template.ParseFS(indexHTML, "templates/requested.html"))
|
|
file, _ := os.ReadFile(config.RequestsFile)
|
|
requests, _ := csv.NewReader(bytes.NewReader(file)).ReadAll()
|
|
|
|
tmpl.Execute(w, struct{ Requests [][]string }{requests})
|
|
}
|
|
|
|
func setupRoutes() {
|
|
http.HandleFunc("/", handleForm)
|
|
http.HandleFunc("/requested", handleRequested)
|
|
err := http.ListenAndServe(config.Listen, nil)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func insertEntry(entry string) {
|
|
f, err := os.OpenFile(config.RequestsFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
|
if err != nil {
|
|
log.Println(err)
|
|
}
|
|
defer f.Close()
|
|
entryFormatted := fmt.Sprintf("%s\n", entry)
|
|
if _, err := f.WriteString(entryFormatted); err != nil {
|
|
log.Println(err)
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
requestsFile := flag.String("requests", "./requests.txt", "Where the file containing all the requests is")
|
|
listen := flag.String("listen", ":8080", "The listen address and port")
|
|
flag.Parse()
|
|
|
|
config.RequestsFile = *requestsFile
|
|
config.Listen = *listen
|
|
|
|
setupRoutes()
|
|
}
|