OSDN Git Service

Update Go library to r60.
[pf3gnuchains/gcc-fork.git] / libgo / go / 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         "os"
12         "sort"
13         "strings"
14 )
15
16 // A Header represents the key-value pairs in an HTTP header.
17 type Header map[string][]string
18
19 // Add adds the key, value pair to the header.
20 // It appends to any existing values associated with key.
21 func (h Header) Add(key, value string) {
22         textproto.MIMEHeader(h).Add(key, value)
23 }
24
25 // Set sets the header entries associated with key to
26 // the single element value.  It replaces any existing
27 // values associated with key.
28 func (h Header) Set(key, value string) {
29         textproto.MIMEHeader(h).Set(key, value)
30 }
31
32 // Get gets the first value associated with the given key.
33 // If there are no values associated with the key, Get returns "".
34 // Get is a convenience method.  For more complex queries,
35 // access the map directly.
36 func (h Header) Get(key string) string {
37         return textproto.MIMEHeader(h).Get(key)
38 }
39
40 // Del deletes the values associated with key.
41 func (h Header) Del(key string) {
42         textproto.MIMEHeader(h).Del(key)
43 }
44
45 // Write writes a header in wire format.
46 func (h Header) Write(w io.Writer) os.Error {
47         return h.WriteSubset(w, nil)
48 }
49
50 // WriteSubset writes a header in wire format.
51 // If exclude is not nil, keys where exclude[key] == true are not written.
52 func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) os.Error {
53         keys := make([]string, 0, len(h))
54         for k := range h {
55                 if exclude == nil || !exclude[k] {
56                         keys = append(keys, k)
57                 }
58         }
59         sort.Strings(keys)
60         for _, k := range keys {
61                 for _, v := range h[k] {
62                         v = strings.Replace(v, "\n", " ", -1)
63                         v = strings.Replace(v, "\r", " ", -1)
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) }