github.com/xmidt-org/webpa-common@v1.11.9/xhttp/xcontext/populate.go (about)

     1  package xcontext
     2  
     3  import (
     4  	"net/http"
     5  
     6  	gokithttp "github.com/go-kit/kit/transport/http"
     7  )
     8  
     9  // Populate accepts any number of go-kit request functions and returns an Alice-style constructor that
    10  // uses the request functions to build a context.  The resulting context is then assocated with the request
    11  // prior to the next http.Handler being invoked.
    12  //
    13  // This function mimics the behavior of go-kit's transport/http package without requiring and endpoint with
    14  // encoding and decoding.
    15  func Populate(rf ...gokithttp.RequestFunc) func(http.Handler) http.Handler {
    16  	if len(rf) > 0 {
    17  		return func(next http.Handler) http.Handler {
    18  			return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
    19  				ctx := Context(response, request)
    20  				for _, f := range rf {
    21  					ctx = f(ctx, request)
    22  				}
    23  
    24  				response, request = WithContext(response, request, ctx)
    25  				next.ServeHTTP(response, request)
    26  			})
    27  		}
    28  	}
    29  
    30  	return func(next http.Handler) http.Handler {
    31  		return next
    32  	}
    33  }