github.com/ethereum/go-ethereum@v1.14.3/rpc/context_headers.go (about)

     1  // Copyright 2022 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"context"
    21  	"net/http"
    22  )
    23  
    24  type mdHeaderKey struct{}
    25  
    26  // NewContextWithHeaders wraps the given context, adding HTTP headers. These headers will
    27  // be applied by Client when making a request using the returned context.
    28  func NewContextWithHeaders(ctx context.Context, h http.Header) context.Context {
    29  	if len(h) == 0 {
    30  		// This check ensures the header map set in context will never be nil.
    31  		return ctx
    32  	}
    33  
    34  	var ctxh http.Header
    35  	prev, ok := ctx.Value(mdHeaderKey{}).(http.Header)
    36  	if ok {
    37  		ctxh = setHeaders(prev.Clone(), h)
    38  	} else {
    39  		ctxh = h.Clone()
    40  	}
    41  	return context.WithValue(ctx, mdHeaderKey{}, ctxh)
    42  }
    43  
    44  // headersFromContext is used to extract http.Header from context.
    45  func headersFromContext(ctx context.Context) http.Header {
    46  	source, _ := ctx.Value(mdHeaderKey{}).(http.Header)
    47  	return source
    48  }
    49  
    50  // setHeaders sets all headers from src in dst.
    51  func setHeaders(dst http.Header, src http.Header) http.Header {
    52  	for key, values := range src {
    53  		dst[http.CanonicalHeaderKey(key)] = values
    54  	}
    55  	return dst
    56  }