douchibu7040 2014-03-21 14:33
浏览 162
已采纳

如何在Go中解析HTTP标头

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?

  • 写回答

1条回答 默认 最新

  • dpwbc42604 2014-03-21 15:22
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!