sessionid.go 937 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package util
  2. import (
  3. "context"
  4. "go-common/library/ecode"
  5. bm "go-common/library/net/http/blademaster"
  6. )
  7. const (
  8. _ajsSessioID = "_AJSESSIONID"
  9. )
  10. type sessionKeyT string
  11. var sessionKey sessionKeyT = "sessionID"
  12. // SessionIDMiddleware extrace session from cookie set to context
  13. func SessionIDMiddleware(c *bm.Context) {
  14. cookie, err := c.Request.Cookie(_ajsSessioID)
  15. if err != nil {
  16. c.JSON(nil, ecode.AccessDenied)
  17. c.Abort()
  18. return
  19. }
  20. c.Context = SessionIDWithContext(c.Context, cookie.Value)
  21. }
  22. // SessionIDFromContext get session id from context
  23. func SessionIDFromContext(ctx context.Context) string {
  24. if val := ctx.Value(sessionKey); val != nil {
  25. if sessionID, ok := val.(string); ok {
  26. return sessionID
  27. }
  28. }
  29. return ""
  30. }
  31. // SessionIDWithContext set session id to context
  32. func SessionIDWithContext(ctx context.Context, sessionID string) context.Context {
  33. return context.WithValue(ctx, sessionKey, sessionID)
  34. }