http.ReadRequest后的Body字段为空,请大家帮忙

sheepbao · 2016-08-23 10:27:55 · 2847 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2016-08-23 10:27:55 的主题,其中的信息可能已经有所发展或是发生改变。

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是怎么赋值的


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2847 次点击  
加入收藏 微博
2 回复  |  直到 2016-08-23 11:44:23
polaris
polaris · #1 · 9年之前

加上这个头:Content-Length: 8

sheepbao
sheepbao · #2 · 9年之前
polarispolaris #1 回复

加上这个头:`Content-Length: 8`

额,还真是,非常感谢

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传