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
1 changed files with 21 additions and 4 deletions

25
main.go
View File

@ -4,6 +4,7 @@ import (
"bytes"
"embed"
"encoding/csv"
"flag"
"fmt"
"html/template"
"log"
@ -18,8 +19,14 @@ type EmojiDetails struct {
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"))
@ -43,7 +50,7 @@ func handleForm(w http.ResponseWriter, r *http.Request) {
func handleRequested(w http.ResponseWriter, r *http.Request) {
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()
tmpl.Execute(w, struct{ Requests [][]string }{requests})
@ -52,12 +59,15 @@ func handleRequested(w http.ResponseWriter, r *http.Request) {
func setupRoutes() {
http.HandleFunc("/", handleForm)
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) {
f, err := os.OpenFile("requests.txt",
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
f, err := os.OpenFile(config.RequestsFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
}
@ -69,5 +79,12 @@ func insertEntry(entry string) {
}
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()
}