```go
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
)
func ParseReq(b []byte) (*http.Request, error) {
// func ReadRequest(b *bufio.Reader) (req *Request, err error) { return readRequest(b, deleteHostHeader) }
var buf io.ReadWriter
buf = new(bytes.Buffer)
buf.Write(b)
bufr := bufio.NewReader(buf)
return http.ReadRequest(bufr)
}
func main() {
context := []byte(
`POST http://www.hh.com/login HTTP/1.1
Accept: */*
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
User-Agent: curl/7.47.0
name=bao`)
req, err := ParseReq(context)
if err != nil {
fmt.Println("parse error, ", err)
}
fmt.Printf("req:---->%#v\n", req)
if req.Method == "POST" {
fmt.Println("URLEncoded form")
body, err := ioutil.ReadAll(req.Body)
if err != nil {
fmt.Println("readall error, ", err)
}
fmt.Println(string(body)) //why empty?
// err := req.ParseForm()
}
}
```
输出结果
```
req:---->&http.Request{Method:"POST", URL:(*url.URL)(0xc82007a080), Proto:"HTTP/1.1", ProtoMajor:1, ProtoMinor:1, Header:http.Header{"Accept":[]string{"*/*"}, "Connection":[]string{"Keep-Alive"}, "Content-Type":[]string{"application/x-www-form-urlencoded"}, "User-Agent":[]string{"curl/7.47.0"}}, Body:(*struct { http.eofReaderWithWriteTo; io.Closer })(0x91fbb0), ContentLength:0, TransferEncoding:[]string(nil), Close:false, Host:"www.hh.com", Form:url.Values(nil), PostForm:url.Values(nil), MultipartForm:(*multipart.Form)(nil), Trailer:http.Header(nil), RemoteAddr:"", RequestURI:"http://www.hh.com/login", TLS:(*tls.ConnectionState)(nil), Cancel:(<-chan struct {})(nil)}
URLEncoded form
```
不知道为何body为空,看了源码也不清楚,没看懂源码的Body是怎么赋值的
有疑问加站长微信联系(非本文作者)