pajenerator/main.go

98 lines
2.1 KiB
Go
Raw Permalink Normal View History

2024-01-23 00:55:15 +01:00
package main
import (
"encoding/json"
"flag"
"html/template"
"log"
"net/http"
)
// Server configs.
var (
listenAddr = flag.String("listen", "0.0.0.0:80", "Listen address for server, in the form addr:port")
scriptPath = flag.String("script", "./pajen.pl", "The relative path to pajen.pl. Must be executable!")
apiQty = flag.Int("quantity", 5, "The number of names returned at a time from the API")
)
var (
pajen *Pajen
indexTmpl = template.Must(template.ParseFiles("index.gohtml"))
)
2024-01-23 01:05:55 +01:00
func logRequest(response int, r *http.Request) {
log.Printf("[%s] %s %s %d", r.RemoteAddr, r.Method, r.RequestURI, response)
}
2024-01-23 00:55:15 +01:00
func handleRoot(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/" {
2024-01-23 01:05:55 +01:00
logRequest(404, r)
2024-01-23 00:55:15 +01:00
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 not found"))
return
}
2024-01-23 01:05:55 +01:00
logRequest(200, r)
2024-01-23 00:55:15 +01:00
indexTmpl.Execute(w, nil)
}
func handleAPI(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" || r.RequestURI != "/api" {
2024-01-23 01:05:55 +01:00
logRequest(404, r)
2024-01-23 00:55:15 +01:00
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 not found"))
return
}
a := make([]string, 0, *apiQty)
for i := 0; i < *apiQty; i++ {
a = append(a, <-pajen.Chan)
}
b, err := json.Marshal(a)
if err != nil {
2024-01-23 01:05:55 +01:00
logRequest(500, r)
2024-01-23 00:55:15 +01:00
w.WriteHeader(http.StatusInternalServerError)
b, _ = json.Marshal(map[string]any{
"status": "Failed",
"error": err,
})
}
2024-01-23 01:05:55 +01:00
logRequest(200, r)
2024-01-23 00:55:15 +01:00
w.Write(b)
}
func main() {
log.Println("Starting pajen.pl frontend - the famous indian name generator")
flag.Parse()
p, err := NewPajen(*scriptPath)
if err != nil {
log.Fatal(err)
}
pajen = p
http.HandleFunc("/", handleRoot)
http.HandleFunc("/api", handleAPI)
http.HandleFunc("/index.css", func(w http.ResponseWriter, r *http.Request) {
2024-01-23 01:05:55 +01:00
logRequest(200, r)
2024-01-23 00:55:15 +01:00
http.ServeFile(w, r, "index.css")
})
http.HandleFunc("/index.js", func(w http.ResponseWriter, r *http.Request) {
2024-01-23 01:05:55 +01:00
logRequest(200, r)
2024-01-23 00:55:15 +01:00
http.ServeFile(w, r, "index.js")
})
2024-01-23 01:08:24 +01:00
http.HandleFunc("/ijeet.jpg", func(w http.ResponseWriter, r *http.Request) {
logRequest(200, r)
http.ServeFile(w, r, "ijeet.jpg")
})
2024-01-23 00:55:15 +01:00
if err := http.ListenAndServe(*listenAddr, nil); err != nil {
log.Fatalln(err)
}
}