当前位置: 代码网 > it编程>前端脚本>Golang > Golang语言如何读取http.Request中body的内容

Golang语言如何读取http.Request中body的内容

2024年05月15日 Golang 我要评论
golang读取http.request中body内容不罗嗦了,直接贴代码,不晓得为什么搞这么复杂,是不是因为担心 body 内容一次接受不全,所以搞了个接口来读取其中的内容?import (..."

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自动关闭的问题。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com