Why does request.ParseForm() drain the request.Body?

huangapple go评论85阅读模式
英文:

Why does request.ParseForm() drain the request.Body?

问题

在这段代码中,如果我注释掉ParseForm()的调用,请求会按预期工作。

但是,如果我调用ParseForm(),则请求的主体将被清空,并且我会得到以下错误信息:

Post http://httpbin.org/post: http: Request.ContentLength=14 with Body length 0

就好像请求的主体长度已经被清空了一样。我该如何访问表单值?我需要创建请求的签名。除了直接从参数中创建签名之外,还有其他方法吗?

英文:

In this code, if I comment the ParseForm() invocation the request works as expected

package main

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"
)

func main() {

	v := make(url.Values)
	v.Set("status", "yeah!")
	request, error := http.NewRequest("POST", "http://httpbin.org/post", strings.NewReader(v.Encode()))
	if error != nil {
		fmt.Println(error)
	}

	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	err:=request.ParseForm()
	if err != nil {
		fmt.Println(err)	
	}
	fmt.Println(request.Form["status"])

	response, error := http.DefaultClient.Do(request)
	if error != nil {
		fmt.Println(error)
	} else {
		fmt.Println(response)
	}
}

But if I call ParseForm() the body is cleared and I get:

Post http://httpbin.org/post: http: Request.ContentLength=14 with Body length 0

Is like the Body length has been drained. How can I access the form values? I need to create a signature of the request. Is there other way (other than creating the signature directly from the parameters directly? )

答案1

得分: 1

使用ParseForm来读取请求,而不是设置。对于简单的POST请求,你可以这样做:

resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})

参考链接:
http://golang.org/pkg/net/http/#Post
http://golang.org/pkg/net/http/#PostForm

英文:

Use ParseForm for read the request, not set.
For simple POST you can do:

resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})

http://golang.org/pkg/net/http/#Post
http://golang.org/pkg/net/http/#PostForm

huangapple
  • 本文由 发表于 2014年5月21日 10:50:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/23773183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定