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