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 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路