Fix error with session not loading

This commit is contained in:
Peter Stuifzand 2021-08-18 20:11:32 +02:00
parent 2a0a582d7b
commit f086d9d9f9
2 changed files with 17 additions and 4 deletions

View File

@ -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

View File

@ -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 {