github.com/craicoverflow/tyk@v2.9.6-rc3+incompatible/test/goplugins/test_goplugin.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "net/http" 6 "sync" 7 8 "github.com/TykTechnologies/tyk/ctx" 9 "github.com/TykTechnologies/tyk/headers" 10 "github.com/TykTechnologies/tyk/user" 11 ) 12 13 // MyPluginPre checks if session is NOT present, adds custom header 14 // with initial URI path and will be used as "pre" custom MW 15 func MyPluginPre(rw http.ResponseWriter, r *http.Request) { 16 session := ctx.GetSession(r) 17 if session != nil { 18 rw.WriteHeader(http.StatusInternalServerError) 19 return 20 } 21 22 rw.Header().Add(headers.XInitialURI, r.URL.RequestURI()) 23 } 24 25 // MyPluginAuthCheck does custom auth and will be used as 26 // "auth_check" custom MW 27 func MyPluginAuthCheck(rw http.ResponseWriter, r *http.Request) { 28 // perform auth (only one token "abc" is allowed) 29 token := r.Header.Get(headers.Authorization) 30 if token != "abc" { 31 rw.Header().Add(headers.XAuthResult, "failed") 32 rw.WriteHeader(http.StatusForbidden) 33 return 34 } 35 36 // create session 37 session := &user.SessionState{ 38 OrgID: "default", 39 Alias: "abc-session", 40 Mutex: &sync.RWMutex{}, 41 } 42 ctx.SetSession(r, session, token, true) 43 44 rw.Header().Add(headers.XAuthResult, "OK") 45 } 46 47 // MyPluginPostKeyAuth checks if session is present, adds custom header with session-alias 48 // and will be used as "post_key_auth" custom MW 49 func MyPluginPostKeyAuth(rw http.ResponseWriter, r *http.Request) { 50 session := ctx.GetSession(r) 51 if session == nil { 52 rw.Header().Add(headers.XSessionAlias, "not found") 53 rw.WriteHeader(http.StatusInternalServerError) 54 return 55 } 56 57 rw.Header().Add(headers.XSessionAlias, session.Alias) 58 } 59 60 // MyPluginPost prepares and sends reply, will be used as "post" custom MW 61 func MyPluginPost(rw http.ResponseWriter, r *http.Request) { 62 63 replyData := map[string]interface{}{ 64 "message": "post message", 65 } 66 67 jsonData, err := json.Marshal(replyData) 68 if err != nil { 69 rw.WriteHeader(http.StatusInternalServerError) 70 return 71 } 72 73 rw.Header().Set(headers.ContentType, headers.ApplicationJSON) 74 rw.WriteHeader(http.StatusOK) 75 rw.Write(jsonData) 76 } 77 78 func main() {}