doumu8911 2018-01-19 08:00
浏览 100
已采纳

将Reader返回到http.Response的函数

This is a stripped-down version of the code I want to use for a page-specific web crawler. The idea is to have a function that gets a URL, deals with HTTP and returns a Reader to the response body http.Response:

package main

import (
    "io"
    "log"
    "net/http"
    "os"
)

func main() {
    const url = "https://xkcd.com/"
    r, err := getPageContent(url)
    if err != nil {
        log.Fatal(err)
    }
    f, err := os.Create("out.html")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    io.Copy(f, r)
}

func getPageContent(url string) (io.Reader, error) {
    res, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    return res.Body, nil
}

The response body is never closed, which is bad. Closing it inside of the getPageContent function won't work, of course, for io.Copy won't be able to read anything from a closed resource.

My question is rather of general interest than for the specific use case: How can I use functions to abstract the gathering of external resources without having to store the whole resource in a temporary buffer? Or should I better avoid such abstractions?

  • 写回答

2条回答 默认 最新

  • duandongji2231 2018-01-19 08:16
    关注

    As pointed out by the user leaf bebop in the comment section, the function getPageCount should return an io.ReadCloser instead of just an io.Reader:

    package main
    
    import (
        "io"
        "log"
        "net/http"
        "os"
    )
    
    func main() {
        const url = "https://xkcd.com/"
        r, err := getPageContent(url)
        if err != nil {
            log.Fatal(err)
        }
        defer r.Close()
        f, err := os.Create("out.html")
        if err != nil {
            log.Fatal(err)
        }
        defer f.Close()
        io.Copy(f, r)
    }
    
    func getPageContent(url string) (io.ReadCloser, error) {
        res, err := http.Get(url)
        if err != nil {
            return nil, err
        }
        return res.Body, nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error