...

Source file src/net/http/header.go

Documentation: net/http

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

View as plain text