API for hosting nethack scores
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

79 lines
1.9 KiB

package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"github.com/gorilla/mux"
"github.com/unixvoid/glogger"
)
var (
loglevel string
recordlocation string
reclistlocation string
port = 8080
)
func main() {
// init runtime args
flag.StringVar(&loglevel, "loglevel", "debug", loglevel)
flag.StringVar(&recordlocation, "recordlocation", "record", recordlocation)
flag.StringVar(&reclistlocation, "reclistlocation", "reclist", reclistlocation)
flag.Parse()
// init config file and logger
initLogger(loglevel)
// make sure record file exists
if _, err := os.Stat(recordlocation); os.IsNotExist(err) {
glogger.Info.Printf("record file not found in %s\n", recordlocation)
fmt.Printf("%s\n", err)
os.Exit(1)
}
// make sure reclist bin exists
if _, err := os.Stat(reclistlocation); os.IsNotExist(err) {
glogger.Info.Printf("reclist binary not found in %s\n", reclistlocation)
fmt.Printf("%s\n", err)
os.Exit(1)
}
// router
router := mux.NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
gethighscore(w, r)
}).Methods("GET")
glogger.Info.Println("nethack-score-api running http on", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), router))
}
func initLogger(loglevel string) {
// init logger
if loglevel == "debug" {
glogger.LogInit(os.Stdout, os.Stdout, os.Stdout, os.Stderr)
} else if loglevel == "cluster" {
glogger.LogInit(os.Stdout, os.Stdout, ioutil.Discard, os.Stderr)
} else if loglevel == "info" {
glogger.LogInit(os.Stdout, ioutil.Discard, ioutil.Discard, os.Stderr)
} else {
glogger.LogInit(ioutil.Discard, ioutil.Discard, ioutil.Discard, os.Stderr)
}
}
func gethighscore(w http.ResponseWriter, r *http.Request) {
// run script
output, err := exec.Command(reclistlocation,
"-f",
recordlocation).CombinedOutput()
if err != nil {
fmt.Printf("%s\n", err)
}
fmt.Fprintf(w, "%s\n", output)
}