ft: add tests

This commit is contained in:
2026-09-06 22:32:59 +03:00
parent 5e23b268a6
commit f8b80081ca
4 changed files with 1208 additions and 22 deletions
+30 -22
View File
@@ -1,31 +1,39 @@
# go-session-redis
Simple HTTP session management
## Example middleware (Chi router)
## Example middleware
```go
func SessionAuthenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, err := session.SessionManager.GetOrCreateSession(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
func SessionAuthenticator(manager *session.Manager, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, err := manager.GetSession(w, r)
if errors.Is(err, session.ErrSessionNotFound) {
http.Error(w, "Not authenticated", http.StatusUnauthorized)
return
}
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
id := s.Get("id")
if id == "" || id == nil {
http.Error(w, "Not authenticated", http.StatusUnauthorized)
return
}
userID, ok := s.Get("user_id").(string)
if !ok || userID == "" {
http.Error(w, "Not authenticated", http.StatusUnauthorized)
return
}
err = s.UpdateTTL()
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
// GetSession refreshes the TTL.
next.ServeHTTP(w, r)
})
}
```
// Session is valid
next.ServeHTTP(w, r)
})
## Creating a session
```go
func CreateAuthenticatedSession(manager *session.Manager, w http.ResponseWriter, r *http.Request, userID string) error {
s, err := manager.CreateSession(w, r)
if err != nil {
return err
}
return s.Set("user_id", userID)
}
```