github.com/craicoverflow/tyk@v2.9.6-rc3+incompatible/ctx/ctx.go (about) 1 package ctx 2 3 import ( 4 "context" 5 "net/http" 6 7 "github.com/TykTechnologies/tyk/apidef" 8 9 "github.com/TykTechnologies/tyk/storage" 10 "github.com/TykTechnologies/tyk/user" 11 ) 12 13 type Key uint 14 15 const ( 16 SessionData Key = iota 17 UpdateSession 18 AuthToken 19 HashedAuthToken 20 VersionData 21 VersionDefault 22 OrgSessionContext 23 ContextData 24 RetainHost 25 TrackThisEndpoint 26 DoNotTrackThisEndpoint 27 UrlRewritePath 28 RequestMethod 29 OrigRequestURL 30 LoopLevel 31 LoopLevelLimit 32 ThrottleLevel 33 ThrottleLevelLimit 34 Trace 35 CheckLoopLimits 36 UrlRewriteTarget 37 TransformedRequestMethod 38 Definition 39 RequestStatus 40 ) 41 42 func setContext(r *http.Request, ctx context.Context) { 43 r2 := r.WithContext(ctx) 44 *r = *r2 45 } 46 47 func ctxSetSession(r *http.Request, s *user.SessionState, token string, scheduleUpdate bool) { 48 if s == nil { 49 panic("setting a nil context SessionData") 50 } 51 52 if token == "" { 53 token = GetAuthToken(r) 54 } 55 56 if s.KeyHashEmpty() { 57 s.SetKeyHash(storage.HashKey(token)) 58 } 59 60 ctx := r.Context() 61 ctx = context.WithValue(ctx, SessionData, s) 62 ctx = context.WithValue(ctx, AuthToken, token) 63 64 if scheduleUpdate { 65 ctx = context.WithValue(ctx, UpdateSession, true) 66 } 67 68 setContext(r, ctx) 69 } 70 71 func GetAuthToken(r *http.Request) string { 72 if v := r.Context().Value(AuthToken); v != nil { 73 return v.(string) 74 } 75 return "" 76 } 77 78 func GetSession(r *http.Request) *user.SessionState { 79 if v := r.Context().Value(SessionData); v != nil { 80 return v.(*user.SessionState) 81 } 82 return nil 83 } 84 85 func SetSession(r *http.Request, s *user.SessionState, token string, scheduleUpdate bool) { 86 ctxSetSession(r, s, token, scheduleUpdate) 87 } 88 89 func SetDefinition(r *http.Request, s *apidef.APIDefinition) { 90 ctx := r.Context() 91 ctx = context.WithValue(ctx, Definition, s) 92 setContext(r, ctx) 93 } 94 95 func GetDefinition(r *http.Request) *apidef.APIDefinition { 96 if v := r.Context().Value(Definition); v != nil { 97 return v.(*apidef.APIDefinition) 98 } 99 return nil 100 }