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