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

缓冲区问题不能在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)

图片转代码服务由CSDN问答提供 功能建议

我在golang正文参数的http.NewRequest中传递字符串时遇到了问题。

我得到的错误是:

不能将req.Body(类型字符串)用作io.Reader类型的参数 http.NewRequest: 字符串未实现io.Reader(缺少Read方法)

类似地,在其他一些用例中,需要将Buffer作为 输入而不是特定类型或其数组。 eg,byte []当需要输入时是缓冲区。

错误的含义是什么,解决该错误的方法以及理解golang试图执行的方法。

编辑:这是我写的那一行 遇到问题,未找到任何参考。

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

http .NewRequest(req.Method,req.Url,strings.NewReader(req.Body))解决了这个问题。 我也计划添加答案(作为FYI类型的问题)

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题