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 중국어 웹사이트의 기타 관련 기사를 참조하세요!