Browse Source

Session for 7 days max, clean up at start

Vova Tkach 6 years ago
parent
commit
85283dcbb1
3 changed files with 31 additions and 1 deletions
  1. 3 0
      main.go
  2. 27 0
      session/clean.go
  3. 1 1
      session/session.go

+ 3 - 0
main.go

@@ -41,5 +41,8 @@ func main() {
 		}
 	})
 
+	// Delete expired session files
+	session.Clean("./tmp")
+
 	http.ListenAndServe(":8080", nil)
 }

+ 27 - 0
session/clean.go

@@ -0,0 +1,27 @@
+package session
+
+import (
+	"io/ioutil"
+	"os"
+	"time"
+)
+
+func Clean(tmpdir string) error {
+	files, err := ioutil.ReadDir(tmpdir)
+	if err != nil {
+		return err
+	}
+	now := time.Now()
+	exp := 7 * 24 * time.Hour
+	for _, file := range files {
+		if len(file.Name()) == 40 {
+			if diff := now.Sub(file.ModTime()); diff > exp {
+				err = os.Remove(tmpdir + string(os.PathSeparator) + file.Name())
+				if err != nil {
+					return err
+				}
+			}
+		}
+	}
+	return nil
+}

+ 1 - 1
session/session.go

@@ -52,7 +52,7 @@ func New(w http.ResponseWriter, r *http.Request, tmpdir string) *session {
 			Name:     "session",
 			Value:    sess.i,
 			Path:     "/",
-			Expires:  time.Now().Add(365 * 24 * time.Hour),
+			Expires:  time.Now().Add(7 * 24 * time.Hour),
 			HttpOnly: true,
 		})
 	}