golang读取http.request中body内容
不罗嗦了,直接贴代码,不晓得为什么搞这么复杂,是不是因为担心 body 内容一次接受不全,所以搞了个接口来读取其中的内容?
import (
...
"io/ioutil"
...
)
...
func mypost(w http.responsewriter, r *http.request) {
s, _ := ioutil.readall(r.body) //把 body 内容读入字符串 s
fmt.fprintf(w, "%s", s) //在返回页面中显示内容。
}
...golang http.request复用
针对除了get以外的请求
package main
import (
"net/http"
"strings"
)
func main(){
reader := strings.newreader("hello")
req,_ := http.newrequest("post","http://www.abc.com",reader)
client := http.client{}
client.do(req) // 第一次会请求成功
client.do(req) // 请求失败
}第二次请求会出错
http: contentlength=5 with body length 0
原因是第一次请求后req.body已经读取到结束位置,所以第二次请求时无法再读取body,
解决方法:
重新定义一个readcloser的实现类替换req.body
package reader
import (
"io"
"net/http"
"strings"
"sync/atomic"
)
type repeat struct{
reader io.readerat
offset int64
}
// read 重写读方法,使每次读取request.body时能从指定位置读取
func (p *repeat) read(val []byte) (n int, err error) {
n, err = p.reader.readat(val, p.offset)
atomic.addint64(&p.offset, int64(n))
return
}
// reset 重置偏移量
func (p *repeat) reset(){
atomic.storeint64(&p.offset,0)
}
func (p *repeat) close() error {
// 因为req.body实现了readcloser接口,所以要实现close方法
// 但是repeat中的值有可能是只读的,所以这里只是尝试关闭一下。
if p.reader != nil {
if rc, ok := p.reader.(io.closer); ok {
return rc.close()
}
}
return nil
}
func dopost() {
client := http.client{}
reader := strings.newreader("hello")
req , _ := http.newrequest("post","http://www.abc.com",reader)
req.body = &repeat{reader:reader,offset:0}
client.do(req)
// 将偏移量重置为0
req.body.(*repeat).reset()
client.do(req)
}这样就不会报错了,因为也重写了close()方法,所以同时也解决了request重用时,req.body自动关闭的问题。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论