duannuochi3549 2018-07-11 16:34
浏览 90
已采纳

在io.ReadCloser中查找字符串而无需进行大量分配

I have a large io.ReadCloser that I got from an http.Request in my HTTP handler func. I need to proxy the request to another server, but first I want to find a string in the body matching a regex like Title: (\w+). This is hard -- copying the whole body into a new buffer to operate on takes up way too much memory, and I've tried using regexp.FindReaderSubmatchIndex but it only gives me the index of the result, not the actual string.

What's the best way to do this? Tokenizers and JSON decoders and such seem to work on io streams, and this is a really simple use case for that. Can someone please point me in the right direction?

  • 写回答

2条回答 默认 最新

  • doushaju4901 2018-07-12 14:03
    关注

    Here's my solution. I placed a pipe between the response body and its reader, and wrapped the reader with an io.TeeReader so it would write to the pipe as I read from it. I wrapped that in a bufio.Scanner and scanned lines. After I was done scanning lines, I was sure to consume the remainder of the body (with io.Copy(ioutil.Discard, body)) so that the rest of the body would be written to the pipe.

    if request.Body == nil {
        proxy(request)
        return
    }
    
    // The body is *not* nil,
    // so we're going to process it line-by-line.
    
    bodySrc := request.Body             // Original io source of the request body.
    pr, pw := io.Pipe()                 // Pipe between bodySrc and request.Body.
    body := io.TeeReader(bodySrc, pw)   // When you read from body, it will read from bodySrc and writes to the pipe.
    request.Body = ioutil.NopCloser(pr) // The other end of the pipe is request.Body. That's what proxy() will read.
    
    go func() {
    
        scanner = bufio.NewScanner(body)
        for scanner.Scan() {
            x := scanner.Bytes()
            if processLine(x) {
                break
            }
        }
    
        // We're done with the body,
        // so consume the rest of it and close the source and the pipe.
        io.Copy(ioutil.Discard, body)
        bodySrc.Close()
        pw.Close()
    
    }()
    
    // As proxy reads request.Body, it's actually keeping up
    // with the scanning done in the above goroutine.
    proxy(request)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序