emojiquest/main.go
2023-12-18 13:32:51 +01:00

64 lines
1.1 KiB
Go

package main
import (
"embed"
"fmt"
"html/template"
"log"
"net/http"
"os"
"strings"
"time"
)
type EmojiDetails struct {
Label string
Url string
}
//go:embed templates
var indexHTML embed.FS
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("label"),
Url: r.FormValue("url"),
}
now := time.Now().UTC().Format(time.RFC3339)
entry := strings.Join([]string{now, details.Label, details.Url}, ",")
log.Print("inserting: ", entry)
insertEntry(entry)
tmpl.Execute(w, struct{ Success bool }{true})
}
func setupRoutes() {
http.HandleFunc("/", handleForm)
http.ListenAndServe(":8080", nil)
}
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)
}
}
func main() {
setupRoutes()
}