github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/matcher/header_stringer.go (about)

     1  package matcher
     2  
     3  import (
     4  	"net/http"
     5  	"sort"
     6  	"strings"
     7  )
     8  
     9  // HeaderStringer turns a http.Header into a fmt.Stringer. It is useful when it's desired to defer string formatting of
    10  // the header depending on loglevel, for instance:
    11  //
    12  //	dlog.Debugf(c, "Header = %s", HeaderStringer(header))
    13  //
    14  // would not perform the actual formatting unless the loglevel is DEBUG or higher.
    15  type HeaderStringer http.Header
    16  
    17  // String formats the Header to a readable multi-line string.
    18  func (s HeaderStringer) String() string {
    19  	h := http.Header(s)
    20  	sb := strings.Builder{}
    21  	ks := make([]string, len(h))
    22  	i := 0
    23  	for k := range h {
    24  		ks[i] = k
    25  		i++
    26  	}
    27  	sort.Strings(ks)
    28  	for i, k := range ks {
    29  		if i > 0 {
    30  			sb.WriteByte('\n')
    31  		}
    32  		sb.WriteString(k)
    33  		sb.WriteString(": ")
    34  		for p, v := range h[k] {
    35  			if p > 0 {
    36  				sb.WriteByte(',')
    37  			}
    38  			sb.WriteString(v)
    39  		}
    40  	}
    41  	return sb.String()
    42  }