> 백엔드 개발 > Golang > Go에서 HTTP 요청과 텍스트 파일의 응답을 어떻게 구문 분석할 수 있나요?

Go에서 HTTP 요청과 텍스트 파일의 응답을 어떻게 구문 분석할 수 있나요?

Mary-Kate Olsen
풀어 주다: 2025-01-03 04:35:39
원래의
897명이 탐색했습니다.

How Can I Parse HTTP Requests and Responses from a Text File in Go?

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

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿