add runtime configuration, see --help or commit

- where the requests file is
- the listen address and port
This commit is contained in:
fungal 2023-12-18 15:38:44 +01:00
parent 9da55bcde9
commit 1c4142fbda

25
main.go
View file

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"embed" "embed"
"encoding/csv" "encoding/csv"
"flag"
"fmt" "fmt"
"html/template" "html/template"
"log" "log"
@ -18,8 +19,14 @@ type EmojiDetails struct {
Url string Url string
} }
type Config struct {
RequestsFile string
Listen string
}
//go:embed templates //go:embed templates
var indexHTML embed.FS var indexHTML embed.FS
var config Config
func handleForm(w http.ResponseWriter, r *http.Request) { func handleForm(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFS(indexHTML, "templates/index.html")) tmpl := template.Must(template.ParseFS(indexHTML, "templates/index.html"))
@ -43,7 +50,7 @@ func handleForm(w http.ResponseWriter, r *http.Request) {
func handleRequested(w http.ResponseWriter, r *http.Request) { func handleRequested(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFS(indexHTML, "templates/requested.html")) tmpl := template.Must(template.ParseFS(indexHTML, "templates/requested.html"))
file, _ := os.ReadFile("requests.txt") file, _ := os.ReadFile(config.RequestsFile)
requests, _ := csv.NewReader(bytes.NewReader(file)).ReadAll() requests, _ := csv.NewReader(bytes.NewReader(file)).ReadAll()
tmpl.Execute(w, struct{ Requests [][]string }{requests}) tmpl.Execute(w, struct{ Requests [][]string }{requests})
@ -52,12 +59,15 @@ func handleRequested(w http.ResponseWriter, r *http.Request) {
func setupRoutes() { func setupRoutes() {
http.HandleFunc("/", handleForm) http.HandleFunc("/", handleForm)
http.HandleFunc("/requested", handleRequested) http.HandleFunc("/requested", handleRequested)
http.ListenAndServe(":8080", nil) err := http.ListenAndServe(config.Listen, nil)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
} }
func insertEntry(entry string) { func insertEntry(entry string) {
f, err := os.OpenFile("requests.txt", f, err := os.OpenFile(config.RequestsFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
@ -69,5 +79,12 @@ func insertEntry(entry string) {
} }
func main() { 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() setupRoutes()
} }