github.com/dbernstein1/tyk@v2.9.0-beta9-dl-apic+incompatible/gateway/mw_method_transform.go (about)

     1  package gateway
     2  
     3  import (
     4  	"errors"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/TykTechnologies/tyk/apidef"
     9  )
    10  
    11  // TransformMiddleware is a middleware that will apply a template to a request body to transform it's contents ready for an upstream API
    12  type TransformMethod struct {
    13  	BaseMiddleware
    14  }
    15  
    16  func (t *TransformMethod) Name() string {
    17  	return "TransformMethod"
    18  }
    19  
    20  func (t *TransformMethod) EnabledForSpec() bool {
    21  	for _, version := range t.Spec.VersionData.Versions {
    22  		if len(version.ExtendedPaths.MethodTransforms) > 0 {
    23  			return true
    24  		}
    25  	}
    26  	return false
    27  }
    28  
    29  // ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
    30  func (t *TransformMethod) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
    31  	_, versionPaths, _, _ := t.Spec.Version(r)
    32  	found, meta := t.Spec.CheckSpecMatchesStatus(r, versionPaths, MethodTransformed)
    33  	if !found {
    34  		return nil, http.StatusOK
    35  	}
    36  	mmeta := meta.(*apidef.MethodTransformMeta)
    37  	toMethod := strings.ToUpper(mmeta.ToMethod)
    38  
    39  	ctxSetRequestMethod(r, r.Method)
    40  
    41  	switch strings.ToUpper(mmeta.ToMethod) {
    42  	case "GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH":
    43  		r.Method = toMethod
    44  	default:
    45  		return errors.New("Method not allowed"), http.StatusMethodNotAllowed
    46  	}
    47  	return nil, http.StatusOK
    48  }