Skip to content

Commit

Permalink
ctx: inject API definition when using Go plugins (TykTechnologies#2624)
Browse files Browse the repository at this point in the history
This is a potential solution for allowing API definition access from Go plugins:
```go
package main

import (
	"fmt"
	"net/http"

	"github.com/TykTechnologies/tyk/ctx"
)

func main() {}

func MyCustomPlugin(w http.ResponseWriter, r *http.Request) {
	fmt.Println("MyCustomPlugin is called")
	apidef := ctx.GetDefinition(r)
	fmt.Println("apidef=", apidef)
}

```
  • Loading branch information
matiasinsaurralde authored and buger committed Nov 7, 2019
1 parent afb45a8 commit 861856e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
16 changes: 16 additions & 0 deletions ctx/ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"context"
"net/http"

"github.com/TykTechnologies/tyk/apidef"

"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/user"
)
Expand All @@ -29,6 +31,7 @@ const (
ThrottleLevelLimit
Trace
CheckLoopLimits
Definition
)

func setContext(r *http.Request, ctx context.Context) {
Expand Down Expand Up @@ -77,3 +80,16 @@ func GetSession(r *http.Request) *user.SessionState {
func SetSession(r *http.Request, s *user.SessionState, token string, scheduleUpdate bool) {
ctxSetSession(r, s, token, scheduleUpdate)
}

func SetDefinition(r *http.Request, s *apidef.APIDefinition) {
ctx := r.Context()
ctx = context.WithValue(ctx, Definition, s)
setContext(r, ctx)
}

func GetDefinition(r *http.Request) *apidef.APIDefinition {
if v := r.Context().Value(Definition); v != nil {
return v.(*apidef.APIDefinition)
}
return nil
}
5 changes: 5 additions & 0 deletions gateway/mw_go_plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/sirupsen/logrus"

"github.com/TykTechnologies/tyk/ctx"
"github.com/TykTechnologies/tyk/goplugin"
)

Expand Down Expand Up @@ -134,6 +135,10 @@ func (m *GoPluginMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Reque

// call Go-plugin function
t1 := time.Now()

// Inject definition into request context:
ctx.SetDefinition(r, m.Spec.APIDefinition)

m.handler(rw, r)

// calculate latency
Expand Down

0 comments on commit 861856e

Please sign in to comment.