80 lines
1.7 KiB
Go
80 lines
1.7 KiB
Go
|
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"))
|
||
|
)
|
||
|
|
||
|
func handleRoot(w http.ResponseWriter, r *http.Request) {
|
||
|
if r.RequestURI != "/" {
|
||
|
w.WriteHeader(http.StatusNotFound)
|
||
|
w.Write([]byte("404 not found"))
|
||
|
return
|
||
|
}
|
||
|
|
||
|
indexTmpl.Execute(w, nil)
|
||
|
}
|
||
|
|
||
|
func handleAPI(w http.ResponseWriter, r *http.Request) {
|
||
|
if r.Method != "GET" || r.RequestURI != "/api" {
|
||
|
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 {
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
b, _ = json.Marshal(map[string]any{
|
||
|
"status": "Failed",
|
||
|
"error": err,
|
||
|
})
|
||
|
}
|
||
|
|
||
|
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) {
|
||
|
http.ServeFile(w, r, "index.css")
|
||
|
})
|
||
|
http.HandleFunc("/index.js", func(w http.ResponseWriter, r *http.Request) {
|
||
|
http.ServeFile(w, r, "index.js")
|
||
|
})
|
||
|
|
||
|
if err := http.ListenAndServe(*listenAddr, nil); err != nil {
|
||
|
log.Fatalln(err)
|
||
|
}
|
||
|
}
|