github.com/yandex/pandora@v0.5.32/components/providers/http/util/request.go (about) 1 package util 2 3 import ( 4 "fmt" 5 "net/http" 6 "net/textproto" 7 "strings" 8 ) 9 10 var ErrHeaderFormat = fmt.Errorf("header line wrong format: expect [key: value]") 11 var ErrEmptyKey = fmt.Errorf("missing header key") 12 13 func DecodeHeader(h string) (key, value string, err error) { 14 var ok bool 15 if len(h) < 3 || h[0] != '[' || h[len(h)-1] != ']' { 16 err = ErrHeaderFormat 17 return 18 } 19 h = h[1 : len(h)-1] 20 if key, value, ok = strings.Cut(h, ":"); !ok { 21 err = ErrHeaderFormat 22 return 23 } 24 key = strings.TrimSpace(key) 25 if key == "" { 26 err = ErrEmptyKey 27 return 28 } 29 value = strings.TrimSpace(value) 30 return 31 } 32 33 func DecodeHTTPConfigHeaders(headers []string) (configHTTPHeaders http.Header, err error) { 34 var key, value string 35 configHTTPHeaders = make(http.Header) 36 for _, h := range headers { 37 key, value, err = DecodeHeader(h) 38 if err != nil { 39 break 40 } 41 configHTTPHeaders.Add(key, value) 42 } 43 return 44 } 45 46 func EnrichRequestWithHeaders(req *http.Request, headers http.Header) { 47 for key, values := range headers { 48 key = textproto.CanonicalMIMEHeaderKey(key) 49 if _, ok := req.Header[key]; !ok { 50 // special behavior for `Host` header 51 if key == "Host" { 52 if req.Host == "" { 53 req.Host = values[0] 54 } 55 } else { 56 req.Header[key] = values 57 } 58 } 59 } 60 }