Golang获取http Request内容

获取http Request内容

获取http Request的内容,需要io.ReadAll调用读取了request的Body,读取完后,我们的控制器就没有请求内容了,此时应该需要把读取出来的字节重新构造成一个ReadCloser赋值给Body:

import (
	"bytes"
	"io"
	"net/http"
)

func PeekRequest(request *http.Request) ([]byte, error) {
	if request.Body != nil {
		byts, err := io.ReadAll(request.Body) // io.ReadAll as Go 1.16, below please use ioutil.ReadAll
		if err != nil {
			return nil, err
		}
		request.Body = io.NopCloser(bytes.NewReader(byts))
		return byts, nil
	}
	return make([]byte, 0), nil
}
posted @ 2022-11-02 11:17  quanbisen  阅读(761)  评论(0编辑  收藏  举报