在Go 中解析來自文字檔案的HTTP 請求和回應
在Go 中,解析來自文字檔案的HTTP 請求和回應涉及利用內建的-HTTP 解析函數。為此,可以採用以下方法:
func ReadHTTPFromFile(r io.Reader) ([]Connection, error) { // Establish a new buffered reader to process the input. buf := bufio.NewReader(r) // Define a slice that will store HTTP connection information. stream := make([]Connection, 0) // Loop indefinitely to parse request and response pairs until we reach the end of the file. for { // Attempt to parse an HTTP request using ReadRequest. req, err := http.ReadRequest(buf) // Check if we have reached the end of the file or an error occurred. if err == io.EOF { // Break out of the loop since we have reached the end of the file. break } else if err != nil { // Log the error and return the partially parsed stream. log.Println("Error parsing HTTP request:", err) return stream, err } // Now that we have a request, we need to parse the corresponding HTTP response. resp, err := http.ReadResponse(buf, req) // Check for any errors while parsing the response. if err != nil { // Log the error and return the partially parsed stream. log.Println("Error parsing HTTP response:", err) return stream, err } // Copy the response body to a new buffer to preserve it. var b bytes.Buffer io.Copy(&b, resp.Body) // Close the original response body and replace it with a new, non-closing one. resp.Body.Close() resp.Body = ioutil.NopCloser(&b) // Add the connection to our stream. stream = append(stream, Connection{Request: req, Response: resp}) } // Return the parsed stream. return stream, nil }
使用此函數,您可以開啟包含 HTTP 請求和回應的檔案並解析它們。例如:
func main() { // Open a file for reading. file, err := os.Open("http.txt") if err != nil { log.Fatal(err) } // Parse the HTTP requests and responses from the file. stream, err := ReadHTTPFromFile(file) if err != nil { log.Fatal(err) } // Dump a representation of the parsed requests and responses for inspection. for _, c := range stream { reqDump, err := httputil.DumpRequest(c.Request, true) if err != nil { log.Fatal(err) } respDump, err := httputil.DumpResponse(c.Response, true) if err != nil { log.Fatal(err) } fmt.Println(string(reqDump)) fmt.Println(string(respDump)) } }
此程式碼將讀取「http.txt」檔案的內容,解析 HTTP 請求和回應,並轉儲它們的表示形式以供檢查。 Go 標準函式庫提供的 HTTP 解析函數可讓您從文字檔案流中提取和操作請求和回應。
以上是如何在 Go 中解析文字檔案中的 HTTP 請求和回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!