r.PostForm和r.Form始终为空。

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

r.PostForm and r.Form always empty

问题

我有一个非常奇怪的问题,要么是我真的瞎了,要么这是某种错误。我有以下的http.Handler:

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        log.Println("解析表单数据时出错")
        return
    }
    log.Println("打印r.PostForm:")
    for key, values := range r.PostForm { // 遍历map
        for _, value := range values { // 遍历[]string
            log.Println(key, value)
        }
    }
    b, _ := ioutil.ReadAll(r.Body)
    s := string(b)
    log.Println("打印body:", s)
}

现在,当向绑定到此处理程序的URL发送PUT请求,并使用以下表单数据时:

Name=someName
Version=1.0.0
PLanguage=java
GitRepo=someRepo

这总是输出:

打印r.PostForm:
打印body: Name=someName&Version=1.0.0&PLanguage=java&GitRepo=someRepo

我已经试图找到原因已经有2个小时了,但我完全不知道出了什么问题。没有错误解析表单数据,但r.PostForm映射始终为空(我也尝试了r.Form,结果相同)。所以为了调试,我添加了打印body的部分,只是为了确保里面确实有一些数据 - 而且确实有。我真的很感激任何帮助。提前谢谢!

英文:

I have a very strange problem, and i'm either really blind, or this is some kind of a bug. I have the following http.Handler:

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		log.Println("Error while parsing form data")
		return
	}
	log.Println("Printing r.PostForm:")
	for key, values := range r.PostForm { // range over map
		for _, value := range values { // range over []string
			log.Println(key, value)
		}
	}
	b, _ := ioutil.ReadAll(r.Body)
	s := string(b)
	log.Println("Printing body: ",s)
}

Now, when sending a PUT-Request to the url binded to this handler with the following FORM-Data:

Name=someName
Version=1.0.0
PLanguage=java
GitRepo=someRepo

This is ALWAYS the output:

Printing r.PostForm:
Printing body: Name=someName&Version=1.0.0&PLanguage=java&GitRepo=someRepo

I've been trying to find the cause for like 2 hours already and i just have no idea what the heck is wrong here. There is no error parsing the Form-Data, but the r.PostForm map is always empty (i also tried r.Form, with same result). So for debugging i added the part where i print the body, just to make sure there actually is some data in there - and it is. I would really appreciate any help here. Thanks in advance!

答案1

得分: 1

你需要设置'Content-Type'头。

如果没有设置头部,根据RFC 2616将使用"application/octet-stream"。

简而言之,这是一种二进制格式,因此你的请求体将不会被解析为Form

英文:

You need to set the 'Content-Type' header.

If no header is set "application/octet-stream" is used according to RFC 2616.

Long story short that is a binary format so your body will not be parsed into the Form.

huangapple
  • 本文由 发表于 2017年2月3日 05:46:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/42012874.html
匿名

发表评论

匿名网友

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

确定