diff --git a/cmd/server/main.go b/cmd/server/main.go index 6df0828..c7b71a8 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -7,15 +7,13 @@ import ( "net/http" "os" "path/filepath" + "time" + "github.com/alexedwards/scs/v2" "github.com/joho/godotenv" ) -func handler(writer http.ResponseWriter, request *http.Request) { - templ := template.Must(template.ParseFiles("./web/dist/index.html")) - - templ.Execute(writer, nil) -} +var sessionManager *scs.SessionManager func main() { err := godotenv.Load() @@ -23,20 +21,27 @@ func main() { log.Fatal("Error loading .env file") } + // handle authentication + sessionManager = scs.New() + sessionManager.Lifetime = 24 * time.Hour + + // handle frontend views webDir := "./web/dist" fs := http.FileServer(http.Dir(webDir)) - http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { - if request.URL.Path != "/" { - path := filepath.Join(webDir, filepath.Clean(request.URL.Path)) - _, err := os.Stat(path) - if err == nil { - fs.ServeHTTP(writer, request) - return + http.Handle("/", sessionManager.LoadAndSave( + http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path != "/" { + path := filepath.Join(webDir, filepath.Clean(request.URL.Path)) + _, err := os.Stat(path) + if err == nil { + fs.ServeHTTP(writer, request) + return + } } - } - handler(writer, request) - }) + handler(writer, request) + }), + )) port := os.Getenv("HTTP_PORT") if port == "" { @@ -48,3 +53,9 @@ func main() { log.Fatalf("server error: %v", err) } } + +func handler(writer http.ResponseWriter, request *http.Request) { + templ := template.Must(template.ParseFiles("./web/dist/index.html")) + + templ.Execute(writer, nil) +}