doukan3504 2013-07-16 04:19
浏览 594
已采纳

如何在Go http服务器中解析http Get请求正文?

In a Go http server, I can get POST request body. Go net/http package seems to remove GET request body. I know it is better not to use http GET with request body,but I need to handle http GET with request body. Is it possible without changing the standard lib? Please help since I don't want to switch back to C with libevent!

When a client sends a POST with request body, below code will show the body content. But when a client sends a GET with request body, there is nothing in the body.

func handler(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    body, _ := ioutil.ReadAll(r.Body)

    log.Printf("body: %v", string(body))
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}
  • 写回答

1条回答 默认 最新

  • dongqie4402 2013-07-16 13:27
    关注

    Most of the magic happens in transfer.go. Here's what I found that looks relevant in the fixLength func:

    if !isResponse && requestMethod == "GET" {
        // RFC 2616 doesn't explicitly permit nor forbid an
        // entity-body on a GET request so we permit one if
        // declared, but we default to 0 here (not -1 below)
        // if there's no mention of a body.
        return 0, nil
    }
    

    Looks like, as long as your client is ending a Content-Length header, you're all good. If not, the library will assume there's no body on a GET request.

    You're kind of off the edge of the map as your client is doing some pretty unusual/broken stuff. If you can fix the client, that's your best bet.

    That said, if you have a client you need to support that's doing this wrong, you're going to have to roll some things yourself. You don't need to go all the way down to C and libevent. Simply copy the net/http package from the standard library into your project and modify it. Then change your import statements to point at your version of the library.

    Alternatively, if you know that the client is not using keep-alive, you can Hijack the connection and just read whatever's left on the socket.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 matlab中频率调制法代码的解读
  • ¥15 ceph的对象、块、文件相关问题求解答
  • ¥50 如果使用python进行ERA5 10米风场预报检验
  • ¥15 navicat解析mysql密码
  • ¥15 SDAPI(关键词-table)
  • ¥15 unity安卓打包出现问题
  • ¥20 安装catkin时遇到了如下问题请问该如何解决呢
  • ¥15 VAE模型如何输出结果
  • ¥15 编译python程序为pyd文件报错:{"source code string cannot contain null bytes"
  • ¥20 关于#r语言#的问题:广义加行模型拟合曲线后如何求拐点
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部