github.com/msales/pkg/v3@v3.24.0/httpx/middleware/context.go (about)

     1  package middleware
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  )
     7  
     8  // WithContext set the context on the request.
     9  func WithContext(ctx context.Context, h http.Handler) http.Handler {
    10  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    11  		h.ServeHTTP(w, r.WithContext(withValueContext(r.Context(), ctx)))
    12  	})
    13  }
    14  
    15  // mergedContext represents a context that merges a parent with a value context.
    16  type mergedContext struct {
    17  	context.Context
    18  
    19  	valueCtx context.Context
    20  }
    21  
    22  // mergeContexts returns a new context which is child of the two passed contexts.
    23  //
    24  // Done() returns the channel from the parent context.
    25  //
    26  // Deadline() returns the deadline from the parent context.
    27  //
    28  // Err() returns the error from the parent context.
    29  //
    30  // Value(key) looks for key in the value context first and falls back to the parent.
    31  func withValueContext(parent, valueCtx context.Context) context.Context {
    32  	return &mergedContext{parent, valueCtx}
    33  }
    34  
    35  // Value returns the value associated with this context for key, or nil.
    36  func (c *mergedContext) Value(key interface{}) interface{} {
    37  	v := c.valueCtx.Value(key)
    38  	if v != nil {
    39  		return v
    40  	}
    41  	return c.Context.Value(key)
    42  }