Hi @Pete I have only one go mod
Below is the complete code
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/sirupsen/logrus"
"github.com/TykTechnologies/tyk/ctx"
"github.com/TykTechnologies/tyk/log"
"github.com/TykTechnologies/tyk/user"
)
const (
authorizationHeader = "Authorization"
)
var (
httpClient = &http.Client{Timeout: time.Second * 10}
logger = log.Get()
policyToApply = "test-policy"
policiesToApply = []string{policyToApply}
)
func init() {
logger.WithFields(logrus.Fields{
"prefix": "HttpCustomAuth",
}).Infof("Intit test http go pligins")
}
func returnResponse(w http.ResponseWriter, errorMessage string, httpStatusCode int) {
jsonData, err := json.Marshal(errorMessage)
if err != nil {
logger.WithFields(logrus.Fields{
"prefix": "HttpCustomAuth",
}).Errorf("Couldn't marshal ", errorMessage)
httpStatusCode = http.StatusInternalServerError
jsonData = []byte("Gateway midlleware error")
}
w.WriteHeader(httpStatusCode)
w.Write(jsonData)
}
func getSession(key string) *user.SessionState {
now := time.Now()
extractorDeadline := time.Now().Add(time.Second * 5).Unix()
return &user.SessionState{
OrgID: "default",
DateCreated: now,
LastUpdated: now.String(),
IdExtractorDeadline: extractorDeadline,
ApplyPolicyID: policyToApply,
ApplyPolicies: policiesToApply,
MetaData: map[string]interface{}{
"token": key,
},
}
}
func callAuthSerive(key string) ([]byte, int, error) {
postBody, _ := json.Marshal(map[string]string{
"name": "test",
"email": key,
})
req, err := http.NewRequest(http.MethodPost, "https://postman-echo.com/post", bytes.NewBuffer(postBody))
if err != nil {
return nil, -1, fmt.Errorf("Got error %s", err.Error())
}
req.Header.Set("user-agent", "tyk golang middleware")
req.Header.Add("Content-Type", "application/json")
req.Header.Add(authorizationHeader, key)
response, err := httpClient.Do(req)
if err != nil {
return nil, -1, fmt.Errorf("Got error %s", err.Error())
}
defer response.Body.Close()
var statusCode = response.StatusCode
body, err := ioutil.ReadAll(response.Body)
return body, statusCode, nil
}
func validateKey(key string) (bool, string, int) {
body, statusCode, err := callAuthSerive(key)
if err != nil || statusCode == -1 {
logger.WithFields(logrus.Fields{
"prefix": "HttpCustomAuth",
}).Errorf("An Error while calling auth service", err)
return false, "Gateway midlleware error while calling auth", 500
}
logger.WithFields(logrus.Fields{
"prefix": "HttpCustomAuth",
}).Infof(string(body))
return true, "", statusCode
}
func HttpCustomAuth(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get(authorizationHeader)
r.Header.Set("X-CUSTOM-HEADER", "Test Custom Header")
if key == "test" {
returnResponse(w, "", http.StatusUnauthorized)
return
}
valid, errorMessage, statusCode := validateKey(key)
if !valid {
returnResponse(w, errorMessage, statusCode)
return
}
ctx.SetSession(r, getSession(key), key, true)
}
func main() {}
I have places below code in this middleware/go/test-http/
directory from project root
this is the command for building the plugin
go build -buildmode=plugin -o <PROJECT_ROOT>/middleware/go/httpCustomAuth.so
And i have specified this plugin in the api configuration as mentioned below