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

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条)

报告相同问题?