github.com/blend/go-sdk@v1.20220411.3/webutil/middleware.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package webutil
     9  
    10  import "net/http"
    11  
    12  // Middleware is a wrapping function that takes a handler and returns a handler.
    13  type Middleware func(http.HandlerFunc) http.HandlerFunc
    14  
    15  // NestMiddleware nests middleware steps.
    16  func NestMiddleware(action http.HandlerFunc, middleware ...Middleware) http.HandlerFunc {
    17  	if len(middleware) == 0 {
    18  		return action
    19  	}
    20  
    21  	var nest = func(a, b Middleware) Middleware {
    22  		if b == nil {
    23  			return a
    24  		}
    25  		return func(inner http.HandlerFunc) http.HandlerFunc {
    26  			return a(b(inner))
    27  		}
    28  	}
    29  
    30  	var outer Middleware
    31  	for _, step := range middleware {
    32  		outer = nest(step, outer)
    33  	}
    34  	return outer(action)
    35  }