github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/plugin/responsetransformer/middleware.go (about)

     1  package responsetransformer
     2  
     3  import (
     4  	"net/http"
     5  )
     6  
     7  type headerFn func(headerName string, headerValue string)
     8  
     9  // Options represents the available options to transform
    10  type Options struct {
    11  	Headers map[string]string `json:"headers"`
    12  }
    13  
    14  // Config represent the configuration of the modify headers middleware
    15  type Config struct {
    16  	Add     Options `json:"add"`
    17  	Append  Options `json:"append"`
    18  	Remove  Options `json:"remove"`
    19  	Replace Options `json:"replace"`
    20  }
    21  
    22  // NewResponseTransformer creates a new instance of RequestTransformer
    23  func NewResponseTransformer(config Config) func(http.Handler) http.Handler {
    24  	return func(next http.Handler) http.Handler {
    25  		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    26  			next.ServeHTTP(w, r)
    27  
    28  			transform(config.Remove.Headers, removeHeaders(w))
    29  			transform(config.Replace.Headers, replaceHeaders(w))
    30  			transform(config.Add.Headers, addHeaders(w))
    31  			transform(config.Append.Headers, appendHeaders(w))
    32  		})
    33  	}
    34  }
    35  
    36  // If and only if the header is not already set, set a new header with the given value. Ignored if the header is already set.
    37  func addHeaders(w http.ResponseWriter) headerFn {
    38  	return func(headerName string, headerValue string) {
    39  		if w.Header().Get(headerName) == "" {
    40  			w.Header().Add(headerName, headerValue)
    41  		}
    42  	}
    43  }
    44  
    45  // If the header is not set, set it with the given value. If it is already set, a new header with the same name and the new value will be set.
    46  func appendHeaders(w http.ResponseWriter) headerFn {
    47  	return func(headerName string, headerValue string) {
    48  		w.Header().Add(headerName, headerValue)
    49  	}
    50  }
    51  
    52  // Unset the headers with the given name.
    53  func removeHeaders(w http.ResponseWriter) headerFn {
    54  	return func(headerName string, headerValue string) {
    55  		w.Header().Del(headerName)
    56  	}
    57  }
    58  
    59  // If and only if the header is already set, replace its old value with the new one. Ignored if the header is not already set.
    60  func replaceHeaders(w http.ResponseWriter) headerFn {
    61  	return func(headerName string, headerValue string) {
    62  		if w.Header().Get(headerName) != "" {
    63  			w.Header().Set(headerName, headerValue)
    64  		}
    65  	}
    66  }
    67  
    68  func transform(values map[string]string, fn headerFn) {
    69  	if len(values) <= 0 {
    70  		return
    71  	}
    72  
    73  	for name, value := range values {
    74  		fn(name, value)
    75  	}
    76  }