1
0
mirror of https://github.com/golang/go synced 2024-11-24 21:10:04 -07:00

net/http: added ParseTime function.

Parses a time header value into a time.Time according to rfc2616 sec 3.3.

R=golang-dev, dave, rsc, r
CC=bradfitz, golang-dev
https://golang.org/cl/6344046
This commit is contained in:
Patrick Higgins 2012-08-31 18:10:16 -04:00 committed by Russ Cox
parent a11b748fa2
commit d168442708
2 changed files with 53 additions and 0 deletions

View File

@ -9,6 +9,7 @@ import (
"net/textproto"
"sort"
"strings"
"time"
)
// A Header represents the key-value pairs in an HTTP header.
@ -53,6 +54,25 @@ func (h Header) Write(w io.Writer) error {
return h.WriteSubset(w, nil)
}
var timeFormats = []string{
TimeFormat,
time.RFC850,
time.ANSIC,
}
// ParseTime parses a time header (such as the Date: header),
// trying each of the three formats allowed by HTTP/1.1:
// TimeFormat, time.RFC850, and time.ANSIC.
func ParseTime(text string) (t time.Time, err error) {
for _, layout := range timeFormats {
t, err = time.Parse(layout, text)
if err == nil {
return
}
}
return
}
var headerNewlineToSpace = strings.NewReplacer("\n", " ", "\r", " ")
type writeStringer interface {

View File

@ -8,6 +8,7 @@ import (
"bytes"
"runtime"
"testing"
"time"
)
var headerWriteTests = []struct {
@ -99,6 +100,38 @@ func TestHeaderWrite(t *testing.T) {
}
}
var parseTimeTests = []struct {
h Header
err bool
}{
{Header{"Date": {""}}, true},
{Header{"Date": {"invalid"}}, true},
{Header{"Date": {"1994-11-06T08:49:37Z00:00"}}, true},
{Header{"Date": {"Sun, 06 Nov 1994 08:49:37 GMT"}}, false},
{Header{"Date": {"Sunday, 06-Nov-94 08:49:37 GMT"}}, false},
{Header{"Date": {"Sun Nov 6 08:49:37 1994"}}, false},
}
func TestParseTime(t *testing.T) {
expect := time.Date(1994, 11, 6, 8, 49, 37, 0, time.UTC)
for i, test := range parseTimeTests {
d, err := ParseTime(test.h.Get("Date"))
if err != nil {
if !test.err {
t.Errorf("#%d:\n got err: %v", i, err)
}
continue
}
if test.err {
t.Errorf("#%d:\n should err", i)
continue
}
if !expect.Equal(d) {
t.Errorf("#%d:\n got: %v\nwant: %v", i, d, expect)
}
}
}
type hasTokenTest struct {
header string
token string