github.com/livekit/protocol@v1.39.3/utils/xtwirp/headers.go (about)

     1  package xtwirp
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  
     7  	"github.com/twitchtv/twirp"
     8  )
     9  
    10  type twirpHeaders struct{}
    11  
    12  func withHeaders(ctx context.Context, h http.Header) context.Context {
    13  	return context.WithValue(ctx, twirpHeaders{}, h)
    14  }
    15  
    16  // GetHeaders returns Twirp headers from the context.
    17  func GetHeaders(ctx context.Context) http.Header {
    18  	if h, ok := twirp.HTTPRequestHeaders(ctx); ok {
    19  		return h
    20  	}
    21  	// Ideally we would just use twirp.HTTPRequestHeaders,
    22  	// but it looks like it's not set in the server context.
    23  	//
    24  	// And using twirp.WithHTTPRequestHeaders requires us to clone headers
    25  	// and get rid of the ones that are not allowed to modify for Twirp.
    26  	h, _ := ctx.Value(twirpHeaders{}).(http.Header)
    27  	return h
    28  }
    29  
    30  // PassHeadersHandler wraps Twirp server handler to allow passing HTTP headers in the context.
    31  func PassHeadersHandler(h http.Handler) http.Handler {
    32  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    33  		ctx := r.Context()
    34  		ctx = withHeaders(ctx, r.Header)
    35  		r = r.WithContext(ctx)
    36  		h.ServeHTTP(w, r)
    37  	})
    38  }