I have http response headers shipped in logs from elsewhere. In my log file I have things like :-
Date: Fri, 21 Mar 2014 06:45:15 GMT
Content-Encoding: gzip
Last-Modified: Tue, 20 Aug 2013 15:45:41 GMT
Server: nginx/0.8.54
Age: 18884
Vary: Accept-Encoding
Content-Type: text/html
Cache-Control: max-age=864000, public
X-UA-Compatible: IE=Edge,chrome=1
Timing-Allow-Origin: *
Content-Length: 14888
Expires: Mon, 31 Mar 2014 06:45:15 GMT
Given the above as string, how go I parse it into Header object as described in net/http . One way would be to split the string myself and map the key, values... But I am looking to avoid doing that by hand and use the standard (or well maintained 3rd party) library to parse it... Any pointers?
The builtin parser is in textproto. You can either use this directly, or add a fake HTTP request header and use ReadRequest in the http package. Either way you need to wrap your data into a bufio.Reader, here I'm just assuming we're starting with a string.
With textproto:
logEntry := "Content-Encoding: gzip
Last-Modified: Tue, 20 Aug 2013 15:45:41 GMT
Server: nginx/0.8.54
Age: 18884
Vary: Accept-Encoding
Content-Type: text/html
Cache-Control: max-age=864000, public
X-UA-Compatible: IE=Edge,chrome=1
Timing-Allow-Origin: *
Content-Length: 14888
Expires: Mon, 31 Mar 2014 06:45:15 GMT
"
// don't forget to make certain the headers end with a second "
"
reader := bufio.NewReader(strings.NewReader(logEntry + "
"))
tp := textproto.NewReader(reader)
mimeHeader, err := tp.ReadMIMEHeader()
if err != nil {
log.Fatal(err)
}
// http.Header and textproto.MIMEHeader are both just a map[string][]string
httpHeader := http.Header(mimeHeader)
log.Println(httpHeader)
and with http.ReadRequest:
logEntry := "Content-Encoding: gzip
Last-Modified: Tue, 20 Aug 2013 15:45:41 GMT
Server: nginx/0.8.54
Age: 18884
Vary: Accept-Encoding
Content-Type: text/html
Cache-Control: max-age=864000, public
X-UA-Compatible: IE=Edge,chrome=1
Timing-Allow-Origin: *
Content-Length: 14888
Expires: Mon, 31 Mar 2014 06:45:15 GMT
"
// we need to make sure to add a fake HTTP header here to make a valid request.
reader := bufio.NewReader(strings.NewReader("GET / HTTP/1.1
" + logEntry + "
"))
logReq, err := http.ReadRequest(reader)
if err != nil {
log.Fatal(err)
}
log.Println(logReq.Header)