From 22e21e02e7d333c9e613456f0c203cd167dba4b1 Mon Sep 17 00:00:00 2001 From: Thibaut Horel Date: Sat, 29 Dec 2018 08:33:36 -0500 Subject: Add command line arguments --- main.go | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) (limited to 'main.go') diff --git a/main.go b/main.go index e38ea1e..e7718a3 100644 --- a/main.go +++ b/main.go @@ -4,10 +4,13 @@ import ( "crypto/md5" "crypto/subtle" "encoding/hex" + "flag" + "fmt" "html/template" "log" "net/http" "os" + "path/filepath" "strconv" "time" ) @@ -15,6 +18,7 @@ import ( type App struct { Store Template *template.Template + Domain string } func logMux(handler http.Handler) http.Handler { @@ -53,7 +57,7 @@ func (app *App) loginHandler(w http.ResponseWriter, r *http.Request) { u, ok := app.GetUser(username) if ok && subtle.ConstantTimeCompare(u.Password, dst) == 1 { s := app.NewSession(u.Id) - c := http.Cookie{Name: "id", Value: s.Id, Domain: ".horel.test"} + c := http.Cookie{Name: "id", Value: s.Id, Domain: "." + app.Domain} http.SetCookie(w, &c) http.Redirect(w, r, next, http.StatusSeeOther) } else { @@ -70,23 +74,37 @@ func (app *App) loginHandler(w http.ResponseWriter, r *http.Request) { } func (app *App) logoutHandler(w http.ResponseWriter, r *http.Request) { - c := http.Cookie{Name: "id", Value: "", Domain: ".horel.test", MaxAge: 0} + c := http.Cookie{Name: "id", Value: "", Domain: "." + app.Domain, MaxAge: 0} http.SetCookie(w, &c) http.Redirect(w, r, "/login", http.StatusSeeOther) } func main() { - //log.SetFlags(log.LstdFlags) - if len(os.Args) == 1 { - log.Fatalf("Usage: %s \n", os.Args[0]) + + flag.Usage = func() { + fmt.Fprintf( + flag.CommandLine.Output(), + "Usage: %s [OPTIONS] [DATABASE] [DOMAIN]\n", + os.Args[0], + ) + flag.PrintDefaults() + } + address := flag.String("a", ":8080", "bind the server to `address`") + templateDir := flag.String("t", "templates", "template `directory`") + flag.Parse() + if flag.NArg() < 2 { + fmt.Print("Argument missing. ") + flag.Usage() + os.Exit(1) } - store := NewPgStore(os.Args[1]) - template := template.Must(template.New("").ParseGlob("templates/*.tmpl")) - app := &App{store, template} + + store := NewPgStore(flag.Args()[0]) + template := template.Must(template.New("").ParseGlob(filepath.Join(*templateDir, "*.tmpl"))) + app := &App{store, template, flag.Args()[1]} http.HandleFunc("/validate", app.validateHandler) http.HandleFunc("/login", app.loginHandler) http.HandleFunc("/logout", app.logoutHandler) - if err := http.ListenAndServe(":8080", logMux(http.DefaultServeMux)); err != nil { + if err := http.ListenAndServe(*address, logMux(http.DefaultServeMux)); err != nil { panic(err) } } -- cgit v1.2.3-70-g09d2