From f086d9d9f9731cf08827617b8117eba2d1d5ed6c Mon Sep 17 00:00:00 2001 From: Peter Stuifzand Date: Wed, 18 Aug 2021 20:11:32 +0200 Subject: [PATCH] Fix error with session not loading --- main.go | 3 +++ session.go | 18 ++++++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 1050944..9269a5a 100644 --- a/main.go +++ b/main.go @@ -745,6 +745,7 @@ func (h *indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { sess, err := NewSession(w, r) if err != nil { + log.Println("NewSession", err) http.Error(w, err.Error(), 500) return } @@ -805,6 +806,7 @@ func (h *indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } else if format == "metakv" { so, err := createStructuredFormat(mpPage) if err != nil { + log.Println("createStructuredFormat", err) http.Error(w, err.Error(), 500) return } @@ -814,6 +816,7 @@ func (h *indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { enc.SetIndent("", " ") err = enc.Encode(so) if err != nil { + log.Println("Encode", err) http.Error(w, err.Error(), 500) } return diff --git a/session.go b/session.go index d11e8cb..9628ad3 100644 --- a/session.go +++ b/session.go @@ -24,6 +24,7 @@ import ( "fmt" "net/http" "os" + "sync" "time" ) @@ -40,12 +41,12 @@ type Session struct { func NewSession(w http.ResponseWriter, r *http.Request) (*Session, error) { sessionID, err := getSessionCookie(w, r) if err != nil { - return nil, err + return nil, fmt.Errorf("getSessionCookie failed: %w", err) } session := &Session{ID: sessionID} err = loadSession(session) if err != nil { - return nil, err + return nil, fmt.Errorf("loadSession failed: %w" , err) } return session, nil } @@ -54,9 +55,13 @@ func (sess *Session) Flush() error { return saveSession(sess) } +var fileMutex sync.RWMutex + func saveSession(sess *Session) error { filename := generateFilename(sess.ID) err := os.Mkdir("session", 0755) + fileMutex.Lock() + defer fileMutex.Unlock() f, err := os.Create(filename) if err != nil { return err @@ -69,17 +74,22 @@ func saveSession(sess *Session) error { func loadSession(sess *Session) error { filename := generateFilename(sess.ID) err := os.Mkdir("session", 0755) + fileMutex.RLock() + defer fileMutex.RUnlock() f, err := os.Open(filename) if err != nil { if os.IsNotExist(err) { // add defaults to session? return nil } - return err + return fmt.Errorf("while opening file %s: %w", filename, err) } defer f.Close() err = json.NewDecoder(f).Decode(sess) - return err + if err != nil { + return fmt.Errorf("while decoding json from file %s: %w", filename, err) + } + return nil } func generateFilename(id string) string {