istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/http/headers/builder.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package headers
    16  
    17  import (
    18  	"net/http"
    19  )
    20  
    21  // Builder for HTTP headers.
    22  type Builder struct {
    23  	headers http.Header
    24  }
    25  
    26  // New Builder for HTTP headers.
    27  func New() *Builder {
    28  	return &Builder{
    29  		headers: make(http.Header),
    30  	}
    31  }
    32  
    33  // Get returns the current value for the key.
    34  func (b *Builder) Get(key string) string {
    35  	return b.headers.Get(key)
    36  }
    37  
    38  // With sets the given header value.
    39  func (b *Builder) With(key, value string) *Builder {
    40  	b.headers.Set(key, value)
    41  	return b
    42  }
    43  
    44  // WithAuthz sets the Authorization header with the given token.
    45  func (b *Builder) WithAuthz(token string) *Builder {
    46  	if token != "" {
    47  		return b.With(Authorization, "Bearer "+token)
    48  	}
    49  	return b
    50  }
    51  
    52  // WithHost sets the Host header to the given value.
    53  func (b *Builder) WithHost(host string) *Builder {
    54  	return b.With(Host, host)
    55  }
    56  
    57  // WithXForwardedFor sets the origin IP of the request.
    58  func (b *Builder) WithXForwardedFor(ip string) *Builder {
    59  	return b.With(XForwardedFor, ip)
    60  }
    61  
    62  func (b *Builder) Build() http.Header {
    63  	if b == nil {
    64  		return nil
    65  	}
    66  
    67  	return b.headers
    68  }
    69  
    70  func (b *Builder) BuildTo(out http.Header) {
    71  	if b == nil {
    72  		return
    73  	}
    74  
    75  	for k, v := range b.headers {
    76  		out[k] = v
    77  	}
    78  }