
在Go 中解析來自文字檔案的HTTP 請求和回應
使用儲存在文字檔案中的HTTP 管道流時,解析請求和響應對於進一步加工至關重要。在本文中,我們將探討如何使用 http.ReadRequest 和 http.ReadResponse 函數在 Go 中有效地實現此目的。
問題
給定一個文字文件,其中包含一系列 HTTP 請求和回應,目標是將這些元件解析為資料結構,特別是 Connection的切片
解決方案
利用上述函數提供了一種簡單的方法來解析文本文件中的請求和回應:
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"os"
)
type Connection struct {
Request *http.Request
Response *http.Response
}
func ReadHTTPFromFile(r io.Reader) ([]Connection, error) {
buf := bufio.NewReader(r)
stream := make([]Connection, 0)
for {
req, err := http.ReadRequest(buf)
if err == io.EOF {
break
}
if err != nil {
return stream, err
}
resp, err := http.ReadResponse(buf, req)
if err != nil {
return stream, err
}
// Save response body
b := new(bytes.Buffer)
io.Copy(b, resp.Body)
resp.Body.Close()
resp.Body = ioutil.NopCloser(b)
stream = append(stream, Connection{Request: req, Response: resp})
}
return stream, nil
}使用方法
要使用此功能,只需閱讀輸入文字即可將檔案寫入閱讀器並呼叫 ReadHTTPFromFile。此函數將傳回 Connection 實例的切片,其中每個連線代表一個請求及其關聯的回應。
f, err := os.Open("/tmp/test.http")
if err != nil {
log.Fatal(err)
}
defer f.Close()
stream, err := ReadHTTPFromFile(f)
if err != nil {
log.Fatalln(err)
}附加說明
以上是如何在 Go 中解析文字檔案中的 HTTP 請求和回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!