duansaoguan7955 2017-11-13 03:03
浏览 432
已采纳

ioutil.ReadAll惨败

I'm trying to get an io.Reader back from this weather it's a link or a path I'm given. For some context I'm using flags

func getString(link, path string) (io.Reader, error) {

    var dick io.ReadWriter

    if link != "" {
        resp, err := http.Get(link)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, resp.Body)
    }

    if path != "" {
        file, err := os.Open(path)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, file)
    }

    return dick, nil

}

and boom

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x46e949]

this bad boy comes along

  • 写回答

3条回答 默认 最新

  • duanqiao1880 2017-11-13 03:41
    关注

    io.ReadWriter is an interface, what you need is an instance of io.ReadWriter to write into (via io.Copy) and return the io.Reader interface off of that.

    One type that comes to mind is a bytes.Buffer. Your code would look like this

    func getString(link, path string) (io.Reader, error) {
    
        dick := bytes.NewBuffer(nil)
    
        if link != "" {
            resp, err := http.Get(link)
            if err != nil {
                return nil, err
            }
    
            io.Copy(dick, resp.Body)
        }
    
        if path != "" {
            file, err := os.Open(path)
            if err != nil {
                return nil, err
            }
    
            io.Copy(dick, file)
        }
    
        return dick, nil
    
    }
    

    You are also swallowing the error from io.Copy which isn't a great idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘