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