How to parse http headers in Go -
i have http response headers shipped in logs elsewhere. in log file have things :-
date: fri, 21 mar 2014 06:45:15 gmt\r\ncontent-encoding: gzip\r\nlast-modified: tue, 20 aug 2013 15:45:41 gmt\r\nserver: nginx/0.8.54\r\nage: 18884\r\nvary: accept-encoding\r\ncontent-type: text/html\r\ncache-control: max-age=864000, public\r\nx-ua-compatible: ie=edge,chrome=1\r\ntiming-allow-origin: *\r\ncontent-length: 14888\r\nexpires: mon, 31 mar 2014 06:45:15 gmt\r\n
given above string, how go parse header object described in net/http . 1 way split string myself , map key, values... looking avoid doing hand , use standard (or maintained 3rd party) library parse it... pointers?
the builtin parser in textproto. can either use directly, or add fake http request header , use readrequest in http package. either way need wrap data bufio.reader, here i'm assuming we're starting string.
with textproto:
logentry := "content-encoding: gzip\r\nlast-modified: tue, 20 aug 2013 15:45:41 gmt\r\nserver: nginx/0.8.54\r\nage: 18884\r\nvary: accept-encoding\r\ncontent-type: text/html\r\ncache-control: max-age=864000, public\r\nx-ua-compatible: ie=edge,chrome=1\r\ntiming-allow-origin: *\r\ncontent-length: 14888\r\nexpires: mon, 31 mar 2014 06:45:15 gmt\r\n" // don't forget make headers end second "\r\n" reader := bufio.newreader(strings.newreader(logentry + "\r\n")) tp := textproto.newreader(reader) mimeheader, err := tp.readmimeheader() if err != nil { log.fatal(err) } // http.header , textproto.mimeheader both map[string][]string httpheader := http.header(mimeheader) log.println(httpheader)
and http.readrequest:
logentry := "content-encoding: gzip\r\nlast-modified: tue, 20 aug 2013 15:45:41 gmt\r\nserver: nginx/0.8.54\r\nage: 18884\r\nvary: accept-encoding\r\ncontent-type: text/html\r\ncache-control: max-age=864000, public\r\nx-ua-compatible: ie=edge,chrome=1\r\ntiming-allow-origin: *\r\ncontent-length: 14888\r\nexpires: mon, 31 mar 2014 06:45:15 gmt\r\n" // need make sure add fake http header here make valid request. reader := bufio.newreader(strings.newreader("get / http/1.1\r\n" + logentry + "\r\n")) logreq, err := http.readrequest(reader) if err != nil { log.fatal(err) } log.println(logreq.header)
Comments
Post a Comment