emojiquest/main.go

74 lines
1.5 KiB
Go
Raw Normal View History

2023-12-18 10:46:41 +00:00
package main
import (
2023-12-18 14:05:18 +00:00
"bytes"
2023-12-18 10:46:41 +00:00
"embed"
2023-12-18 14:05:18 +00:00
"encoding/csv"
2023-12-18 12:32:51 +00:00
"fmt"
2023-12-18 10:46:41 +00:00
"html/template"
"log"
"net/http"
2023-12-18 12:32:51 +00:00
"os"
"strings"
"time"
2023-12-18 10:46:41 +00:00
)
type EmojiDetails struct {
Label string
2023-12-18 11:56:51 +00:00
Url string
2023-12-18 10:46:41 +00:00
}
//go:embed templates
var indexHTML embed.FS
2023-12-18 10:54:21 +00:00
func handleForm(w http.ResponseWriter, r *http.Request) {
2023-12-18 10:46:41 +00:00
tmpl := template.Must(template.ParseFS(indexHTML, "templates/index.html"))
2023-12-18 10:54:21 +00:00
if r.Method != http.MethodPost {
tmpl.Execute(w, nil)
return
}
2023-12-18 10:46:41 +00:00
2023-12-18 10:54:21 +00:00
details := EmojiDetails{
Label: r.FormValue("label"),
2023-12-18 11:56:51 +00:00
Url: r.FormValue("url"),
2023-12-18 10:54:21 +00:00
}
2023-12-18 10:46:41 +00:00
2023-12-18 12:32:51 +00:00
now := time.Now().UTC().Format(time.RFC3339)
2023-12-18 14:05:18 +00:00
entry := strings.Join([]string{now, "unknown", details.Label, details.Url}, ",")
2023-12-18 12:32:51 +00:00
insertEntry(entry)
2023-12-18 10:46:41 +00:00
2023-12-18 10:54:21 +00:00
tmpl.Execute(w, struct{ Success bool }{true})
}
2023-12-18 10:46:41 +00:00
2023-12-18 14:05:18 +00:00
func handleRequested(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFS(indexHTML, "templates/requested.html"))
file, _ := os.ReadFile("requests.txt")
requests, _ := csv.NewReader(bytes.NewReader(file)).ReadAll()
tmpl.Execute(w, struct{ Requests [][]string }{requests})
}
2023-12-18 10:54:21 +00:00
func setupRoutes() {
http.HandleFunc("/", handleForm)
2023-12-18 14:05:18 +00:00
http.HandleFunc("/requested", handleRequested)
2023-12-18 10:46:41 +00:00
http.ListenAndServe(":8080", nil)
}
2023-12-18 10:54:21 +00:00
2023-12-18 12:32:51 +00:00
func insertEntry(entry string) {
f, err := os.OpenFile("requests.txt",
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)
}
}
2023-12-18 10:54:21 +00:00
func main() {
setupRoutes()
}