如何在Go中解析HTTP标头

如何在Go中解析HTTP标头,第1张

如何在Go中解析HTTP标头

内置的解析器位于textproto中。您可以直接使用它,也可以添加伪造的HTTP请求标头并在http包中使用ReadRequest。无论哪种方式,您都需要将数据包装到bufio.Reader中,这里我只是假设我们从字符串开始。

使用textproto:

logEntry := "Content-Encoding: gziprnLast-Modified: Tue, 20 Aug 2013 15:45:41 GMTrnServer: nginx/0.8.54rnAge: 18884rnVary: Accept-EncodingrnContent-Type: text/htmlrnCache-Control: max-age=864000, publicrnX-UA-Compatible: IE=Edge,chrome=1rnTiming-Allow-Origin: *rnContent-Length: 14888rnExpires: Mon, 31 Mar 2014 06:45:15 GMTrn"// don't forget to make certain the headers end with a second "rn"reader := bufio.NewReader(strings.NewReader(logEntry + "rn"))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][]stringhttpHeader := http.Header(mimeHeader)log.Println(httpHeader)

和http.ReadRequest:

logEntry := "Content-Encoding: gziprnLast-Modified: Tue, 20 Aug 2013 15:45:41 GMTrnServer: nginx/0.8.54rnAge: 18884rnVary: Accept-EncodingrnContent-Type: text/htmlrnCache-Control: max-age=864000, publicrnX-UA-Compatible: IE=Edge,chrome=1rnTiming-Allow-Origin: *rnContent-Length: 14888rnExpires: Mon, 31 Mar 2014 06:45:15 GMTrn"// 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.1rn" + logEntry + "rn"))logReq, err := http.ReadRequest(reader)if err != nil {    log.Fatal(err)}log.Println(logReq.Header)


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5086969.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-16
下一篇2022-11-16

发表评论

登录后才能评论

评论列表(0条)

    保存