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