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

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

我得到的错误是:

不能在 http.NewRequest 的参数中使用 req.Body(类型字符串)作为类型 io.Reader:字符串没有实现 io.Reader(缺少读取方法)

类似地,还有其他用例需要 Buffer 作为输入而不是特定类型或它的数组。例如,需要输入时的 byte[] 是缓冲区。

该错误是什么意思,解决它的方法是什么,并了解 golang 试图强制执行的内容。

编辑:这是我遇到问题的行,没有找到任何参考。

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

http.NewRequest(req.Method, req.Url, strings.NewReader(req.Body)) 解决了这个问题。我也打算添加答案(作为仅供参考的问题)


慕娘9325324
浏览 217回答 1
1回答

达令说

此错误意味着该http.NewRequest方法将io.Reader接口作为其body参数:func&nbsp;NewRequest(method,&nbsp;urlStr&nbsp;string,&nbsp;body&nbsp;io.Reader)&nbsp;(*Request,&nbsp;error)这样做是为了让您可以轻松地传递文件、与服务器的连接、来自其他事物的响应对请求的响应。“问题”是 astring没有实现io.Reader接口,接口定义如下:type&nbsp;Reader&nbsp;interface&nbsp;{ &nbsp;&nbsp;&nbsp;Read(p&nbsp;[]byte)&nbsp;(n&nbsp;int,&nbsp;err&nbsp;error)}这不是一个大问题,您可以使用实现上述接口strings.Reader的封装类型string。func&nbsp;NewReader(s&nbsp;string)&nbsp;*Reader提示:还有一个bytes.Reader类型可以用于[]byte作为参数传递的时间。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go