gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmhttp/header.go (about)

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gmhttp
     6  
     7  import (
     8  	"io"
     9  	"net/textproto"
    10  	"sort"
    11  	"strings"
    12  	"sync"
    13  	"time"
    14  
    15  	"gitee.com/ks-custle/core-gm/gmhttp/httptrace"
    16  	"gitee.com/ks-custle/core-gm/gmhttp/internal/ascii"
    17  )
    18  
    19  // A Header represents the key-value pairs in an HTTP header.
    20  //
    21  // The keys should be in canonical form, as returned by
    22  // CanonicalHeaderKey.
    23  type Header map[string][]string
    24  
    25  // Add adds the key, value pair to the header.
    26  // It appends to any existing values associated with key.
    27  // The key is case insensitive; it is canonicalized by
    28  // CanonicalHeaderKey.
    29  func (h Header) Add(key, value string) {
    30  	textproto.MIMEHeader(h).Add(key, value)
    31  }
    32  
    33  // Set sets the header entries associated with key to the
    34  // single element value. It replaces any existing values
    35  // associated with key. The key is case insensitive; it is
    36  // canonicalized by textproto.CanonicalMIMEHeaderKey.
    37  // To use non-canonical keys, assign to the map directly.
    38  func (h Header) Set(key, value string) {
    39  	textproto.MIMEHeader(h).Set(key, value)
    40  }
    41  
    42  // Get gets the first value associated with the given key. If
    43  // there are no values associated with the key, Get returns "".
    44  // It is case insensitive; textproto.CanonicalMIMEHeaderKey is
    45  // used to canonicalize the provided key. To use non-canonical keys,
    46  // access the map directly.
    47  func (h Header) Get(key string) string {
    48  	return textproto.MIMEHeader(h).Get(key)
    49  }
    50  
    51  // Values returns all values associated with the given key.
    52  // It is case insensitive; textproto.CanonicalMIMEHeaderKey is
    53  // used to canonicalize the provided key. To use non-canonical
    54  // keys, access the map directly.
    55  // The returned slice is not a copy.
    56  func (h Header) Values(key string) []string {
    57  	return textproto.MIMEHeader(h).Values(key)
    58  }
    59  
    60  // get is like Get, but key must already be in CanonicalHeaderKey form.
    61  func (h Header) get(key string) string {
    62  	if v := h[key]; len(v) > 0 {
    63  		return v[0]
    64  	}
    65  	return ""
    66  }
    67  
    68  // has reports whether h has the provided key defined, even if it's
    69  // set to 0-length slice.
    70  func (h Header) has(key string) bool {
    71  	_, ok := h[key]
    72  	return ok
    73  }
    74  
    75  // Del deletes the values associated with key.
    76  // The key is case insensitive; it is canonicalized by
    77  // CanonicalHeaderKey.
    78  func (h Header) Del(key string) {
    79  	textproto.MIMEHeader(h).Del(key)
    80  }
    81  
    82  // Write writes a header in wire format.
    83  func (h Header) Write(w io.Writer) error {
    84  	return h.write(w, nil)
    85  }
    86  
    87  func (h Header) write(w io.Writer, trace *httptrace.ClientTrace) error {
    88  	return h.writeSubset(w, nil, trace)
    89  }
    90  
    91  // Clone returns a copy of h or nil if h is nil.
    92  func (h Header) Clone() Header {
    93  	if h == nil {
    94  		return nil
    95  	}
    96  
    97  	// Find total number of values.
    98  	nv := 0
    99  	for _, vv := range h {
   100  		nv += len(vv)
   101  	}
   102  	sv := make([]string, nv) // shared backing array for headers' values
   103  	h2 := make(Header, len(h))
   104  	for k, vv := range h {
   105  		n := copy(sv, vv)
   106  		h2[k] = sv[:n:n]
   107  		sv = sv[n:]
   108  	}
   109  	return h2
   110  }
   111  
   112  var timeFormats = []string{
   113  	TimeFormat,
   114  	time.RFC850,
   115  	time.ANSIC,
   116  }
   117  
   118  // ParseTime parses a time header (such as the Date: header),
   119  // trying each of the three formats allowed by HTTP/1.1:
   120  // TimeFormat, time.RFC850, and time.ANSIC.
   121  func ParseTime(text string) (t time.Time, err error) {
   122  	for _, layout := range timeFormats {
   123  		t, err = time.Parse(layout, text)
   124  		if err == nil {
   125  			return
   126  		}
   127  	}
   128  	return
   129  }
   130  
   131  var headerNewlineToSpace = strings.NewReplacer("\n", " ", "\r", " ")
   132  
   133  // stringWriter implements WriteString on a Writer.
   134  type stringWriter struct {
   135  	w io.Writer
   136  }
   137  
   138  func (w stringWriter) WriteString(s string) (n int, err error) {
   139  	return w.w.Write([]byte(s))
   140  }
   141  
   142  type keyValues struct {
   143  	key    string
   144  	values []string
   145  }
   146  
   147  // A headerSorter implements sort.Interface by sorting a []keyValues
   148  // by key. It's used as a pointer, so it can fit in a sort.Interface
   149  // interface value without allocation.
   150  type headerSorter struct {
   151  	kvs []keyValues
   152  }
   153  
   154  func (s *headerSorter) Len() int           { return len(s.kvs) }
   155  func (s *headerSorter) Swap(i, j int)      { s.kvs[i], s.kvs[j] = s.kvs[j], s.kvs[i] }
   156  func (s *headerSorter) Less(i, j int) bool { return s.kvs[i].key < s.kvs[j].key }
   157  
   158  var headerSorterPool = sync.Pool{
   159  	New: func() interface{} { return new(headerSorter) },
   160  }
   161  
   162  // sortedKeyValues returns h's keys sorted in the returned kvs
   163  // slice. The headerSorter used to sort is also returned, for possible
   164  // return to headerSorterCache.
   165  func (h Header) sortedKeyValues(exclude map[string]bool) (kvs []keyValues, hs *headerSorter) {
   166  	hs = headerSorterPool.Get().(*headerSorter)
   167  	if cap(hs.kvs) < len(h) {
   168  		hs.kvs = make([]keyValues, 0, len(h))
   169  	}
   170  	kvs = hs.kvs[:0]
   171  	for k, vv := range h {
   172  		if !exclude[k] {
   173  			kvs = append(kvs, keyValues{k, vv})
   174  		}
   175  	}
   176  	hs.kvs = kvs
   177  	sort.Sort(hs)
   178  	return kvs, hs
   179  }
   180  
   181  // WriteSubset writes a header in wire format.
   182  // If exclude is not nil, keys where exclude[key] == true are not written.
   183  // Keys are not canonicalized before checking the exclude map.
   184  func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error {
   185  	return h.writeSubset(w, exclude, nil)
   186  }
   187  
   188  func (h Header) writeSubset(w io.Writer, exclude map[string]bool, trace *httptrace.ClientTrace) error {
   189  	ws, ok := w.(io.StringWriter)
   190  	if !ok {
   191  		ws = stringWriter{w}
   192  	}
   193  	kvs, sorter := h.sortedKeyValues(exclude)
   194  	var formattedVals []string
   195  	for _, kv := range kvs {
   196  		for _, v := range kv.values {
   197  			v = headerNewlineToSpace.Replace(v)
   198  			v = textproto.TrimString(v)
   199  			for _, s := range []string{kv.key, ": ", v, "\r\n"} {
   200  				if _, err := ws.WriteString(s); err != nil {
   201  					headerSorterPool.Put(sorter)
   202  					return err
   203  				}
   204  			}
   205  			if trace != nil && trace.WroteHeaderField != nil {
   206  				formattedVals = append(formattedVals, v)
   207  			}
   208  		}
   209  		if trace != nil && trace.WroteHeaderField != nil {
   210  			trace.WroteHeaderField(kv.key, formattedVals)
   211  			formattedVals = nil
   212  		}
   213  	}
   214  	headerSorterPool.Put(sorter)
   215  	return nil
   216  }
   217  
   218  // CanonicalHeaderKey returns the canonical format of the
   219  // header key s. The canonicalization converts the first
   220  // letter and any letter following a hyphen to upper case;
   221  // the rest are converted to lowercase. For example, the
   222  // canonical key for "accept-encoding" is "Accept-Encoding".
   223  // If s contains a space or invalid header field bytes, it is
   224  // returned without modifications.
   225  func CanonicalHeaderKey(s string) string { return textproto.CanonicalMIMEHeaderKey(s) }
   226  
   227  // hasToken reports whether token appears with v, ASCII
   228  // case-insensitive, with space or comma boundaries.
   229  // token must be all lowercase.
   230  // v may contain mixed cased.
   231  func hasToken(v, token string) bool {
   232  	if len(token) > len(v) || token == "" {
   233  		return false
   234  	}
   235  	if v == token {
   236  		return true
   237  	}
   238  	for sp := 0; sp <= len(v)-len(token); sp++ {
   239  		// Check that first character is good.
   240  		// The token is ASCII, so checking only a single byte
   241  		// is sufficient. We skip this potential starting
   242  		// position if both the first byte and its potential
   243  		// ASCII uppercase equivalent (b|0x20) don't match.
   244  		// False positives ('^' => '~') are caught by EqualFold.
   245  		if b := v[sp]; b != token[0] && b|0x20 != token[0] {
   246  			continue
   247  		}
   248  		// Check that start pos is on a valid token boundary.
   249  		if sp > 0 && !isTokenBoundary(v[sp-1]) {
   250  			continue
   251  		}
   252  		// Check that end pos is on a valid token boundary.
   253  		if endPos := sp + len(token); endPos != len(v) && !isTokenBoundary(v[endPos]) {
   254  			continue
   255  		}
   256  		if ascii.EqualFold(v[sp:sp+len(token)], token) {
   257  			return true
   258  		}
   259  	}
   260  	return false
   261  }
   262  
   263  func isTokenBoundary(b byte) bool {
   264  	return b == ' ' || b == ',' || b == '\t'
   265  }