github.com/avenga/couper@v1.12.2/handler/middleware/allowed_methods.go (about)

     1  package middleware
     2  
     3  import (
     4  	"net/http"
     5  	"strings"
     6  )
     7  
     8  var DefaultFileSpaAllowedMethods = []string{
     9  	http.MethodGet,
    10  	http.MethodHead,
    11  }
    12  
    13  var DefaultEndpointAllowedMethods = []string{
    14  	http.MethodGet,
    15  	http.MethodHead,
    16  	http.MethodPost,
    17  	http.MethodPut,
    18  	http.MethodPatch,
    19  	http.MethodDelete,
    20  	http.MethodOptions,
    21  }
    22  
    23  var _ http.Handler = &AllowedMethodsHandler{}
    24  
    25  type AllowedMethodsHandler struct {
    26  	allowedMethods    map[string]struct{}
    27  	allowedHandler    http.Handler
    28  	notAllowedHandler http.Handler
    29  }
    30  
    31  type methodAllowedFunc func(string) bool
    32  
    33  func NewAllowedMethodsHandler(allowedMethods, defaultAllowedMethods []string, allowedHandler, notAllowedHandler http.Handler) *AllowedMethodsHandler {
    34  	amh := &AllowedMethodsHandler{
    35  		allowedMethods:    make(map[string]struct{}),
    36  		allowedHandler:    allowedHandler,
    37  		notAllowedHandler: notAllowedHandler,
    38  	}
    39  	if allowedMethods == nil && defaultAllowedMethods != nil {
    40  		allowedMethods = defaultAllowedMethods
    41  	}
    42  	for _, method := range allowedMethods {
    43  		if method == "*" {
    44  			if defaultAllowedMethods == nil {
    45  				continue
    46  			}
    47  			for _, m := range defaultAllowedMethods {
    48  				amh.allowedMethods[m] = struct{}{}
    49  			}
    50  		} else {
    51  			method = strings.ToUpper(method)
    52  			amh.allowedMethods[method] = struct{}{}
    53  		}
    54  	}
    55  
    56  	return amh
    57  }
    58  
    59  func (a *AllowedMethodsHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    60  	method := strings.ToUpper(req.Method)
    61  	if _, ok := a.allowedMethods[method]; !ok {
    62  		a.notAllowedHandler.ServeHTTP(rw, req)
    63  		return
    64  	}
    65  
    66  	a.allowedHandler.ServeHTTP(rw, req)
    67  }
    68  
    69  func (a *AllowedMethodsHandler) MethodAllowed(method string) bool {
    70  	method = strings.TrimSpace(strings.ToUpper(method))
    71  	_, ok := a.allowedMethods[method]
    72  	return ok
    73  }
    74  
    75  func (a *AllowedMethodsHandler) Child() http.Handler {
    76  	return a.allowedHandler
    77  }