github.com/anuvu/tyk@v2.9.0-beta9-dl-apic+incompatible/test/goplugins/test_goplugin.go (about)

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