package main import ( "encoding/json" "flag" "fmt" "log" "net/http" "os" "strconv" passage "git.bullercodeworks.com/brian/passage-go" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/justinas/alice" ) var port int var ip string func init() { const ( portDefault = 8080 portUsage = "the port to listen on" ipDefault = "127.0.0.1" ipUsage = "the ip mask to listen for connections from" ) flag.StringVar(&ip, "ip", ipDefault, ipUsage) flag.IntVar(&port, "port", portDefault, portUsage) } func main() { flag.Parse() r := mux.NewRouter() r.HandleFunc("/", mainPage) r.HandleFunc("/api/generate", generate) r.HandleFunc("/api/checksum", checksum) chain := alice.New(loggingHandler).Then(r) listenAt := ip + ":" + strconv.Itoa(port) fmt.Println("Passage Server listening at", listenAt) log.Fatal(http.ListenAndServe(listenAt, chain)) } func checksum(w http.ResponseWriter, req *http.Request) { err := req.ParseForm() if err != nil { http.Error(w, err.Error(), 500) return } pin := req.FormValue("pin") p := passage.CreatePassage(pin) w.Write([]byte(p.GetChecksumAsString())) } func generate(w http.ResponseWriter, req *http.Request) { type resp struct { Checksum string Password string Door string Error error } var err error var bts []byte err = req.ParseForm() if err != nil { http.Error(w, err.Error(), 500) return } pin := req.FormValue("pin") door := req.FormValue("door") if pin != "" && door != "" { r := new(resp) p := passage.CreatePassage(pin) r.Checksum = p.GetChecksumAsString() r.Password = p.GetPassword(door) r.Door = door bts, err = json.Marshal(r) if err != nil { http.Error(w, err.Error(), 500) return } } else { http.Error(w, "Both Pin and Door must be provided", 400) return } w.Write(bts) } func mainPage(w http.ResponseWriter, req *http.Request) { err := req.ParseForm() pageString := "" pageString += "" pageString += " " pageString += " Passage" pageString += " " pageString += " " if err != nil { pageString += "
" + err.Error() + "
" } pin := req.FormValue("pin") door := req.FormValue("door") if pin != "" && door != "" { p := passage.CreatePassage(pin) chk := p.GetChecksumAsString() pw := p.GetPassword(door) pageString += "
Checksum: " + chk + "
" + "Password: " + pw + "
" } pageString += "
" pageString += " " pageString += " " pageString += " " pageString += "
" pageString += " " pageString += "" w.Write([]byte(pageString)) } func loggingHandler(h http.Handler) http.Handler { return handlers.LoggingHandler(os.Stdout, h) }