drtiwd06558 2016-05-09 10:03 采纳率: 100%
浏览 483
已采纳

缓冲区问题不能在http.NewRequest golang的参数中将<type>用作类型io.Reader

I was having an issue when I was passing string in http.NewRequest in golang body param.

The error I got was :

cannot use req.Body (type string) as type io.Reader in argument to http.NewRequest: string does not implement io.Reader (missing Read method)

Similarly there are other use cases where the Buffer is required as an input instead of a particular type or an array of it. eg, byte[] when input required is buffer.

What did the error mean and what are ways of solving it and understanding what golang is trying to enforce.

Edit: This was the line I was having an issue with and did not find any references.

http.NewRequest(req.Method, req.Url, req.Body)

http.NewRequest(req.Method, req.Url, strings.NewReader(req.Body)) solves the issue. I was planning to add the answer as well (as an FYI type of question)

  • 写回答

1条回答 默认 最新

  • douzhuiqiu4923 2016-05-09 10:11
    关注

    This error means that the http.NewRequest method take a io.Reader interface as its body argument:

    func NewRequest(method, urlStr string, body io.Reader) (*Request, error)
    

    It is done this way so you can pass a file, a connection to a server, the response from something else to the request easily.

    The "problem" is that a string doesn't implement the io.Reader interface, which is defined as follow:

    type Reader interface {
       Read(p []byte) (n int, err error)
    }
    

    Its not a huge problem, you can use the strings.Reader type which is a wrapper around a string that implement the said interface.

    func NewReader(s string) *Reader
    

    Tip: There also is a bytes.Reader type for the times you have a []byte to pass as parameter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)