src/pkg/net/http/header.go - The Go Programming Language

Golang

Source file src/pkg/net/http/header.go

     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		"fmt"
     9		"io"
    10		"net/textproto"
    11		"sort"
    12		"strings"
    13	)
    14	
    15	// A Header represents the key-value pairs in an HTTP header.
    16	type Header map[string][]string
    17	
    18	// Add adds the key, value pair to the header.
    19	// It appends to any existing values associated with key.
    20	func (h Header) Add(key, value string) {
    21		textproto.MIMEHeader(h).Add(key, value)
    22	}
    23	
    24	// Set sets the header entries associated with key to
    25	// the single element value.  It replaces any existing
    26	// values associated with key.
    27	func (h Header) Set(key, value string) {
    28		textproto.MIMEHeader(h).Set(key, value)
    29	}
    30	
    31	// Get gets the first value associated with the given key.
    32	// If there are no values associated with the key, Get returns "".
    33	// To access multiple values of a key, access the map directly
    34	// with CanonicalHeaderKey.
    35	func (h Header) Get(key string) string {
    36		return textproto.MIMEHeader(h).Get(key)
    37	}
    38	
    39	// Del deletes the values associated with key.
    40	func (h Header) Del(key string) {
    41		textproto.MIMEHeader(h).Del(key)
    42	}
    43	
    44	// Write writes a header in wire format.
    45	func (h Header) Write(w io.Writer) error {
    46		return h.WriteSubset(w, nil)
    47	}
    48	
    49	var headerNewlineToSpace = strings.NewReplacer("\n", " ", "\r", " ")
    50	
    51	// WriteSubset writes a header in wire format.
    52	// If exclude is not nil, keys where exclude[key] == true are not written.
    53	func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error {
    54		keys := make([]string, 0, len(h))
    55		for k := range h {
    56			if exclude == nil || !exclude[k] {
    57				keys = append(keys, k)
    58			}
    59		}
    60		sort.Strings(keys)
    61		for _, k := range keys {
    62			for _, v := range h[k] {
    63				v = headerNewlineToSpace.Replace(v)
    64				v = strings.TrimSpace(v)
    65				if _, err := fmt.Fprintf(w, "%s: %s\r\n", k, v); err != nil {
    66					return err
    67				}
    68			}
    69		}
    70		return nil
    71	}
    72	
    73	// CanonicalHeaderKey returns the canonical format of the
    74	// header key s.  The canonicalization converts the first
    75	// letter and any letter following a hyphen to upper case;
    76	// the rest are converted to lowercase.  For example, the
    77	// canonical key for "accept-encoding" is "Accept-Encoding".
    78	func CanonicalHeaderKey(s string) string { return textproto.CanonicalMIMEHeaderKey(s) }