Go不能同时添加accept和content-type头部。

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

Go can not add accept and content-type headers at the same time

问题

我正在尝试为Go语言中的一个简单REST应用编写测试。所以我写了以下代码:

func TestMyTestFunc(t *testing.T) {
    var w = httptest.NewRecorder()
    req, err := http.NewRequest("POST", "/", nil)
    if err != nil {
        t.Errorf("Error creating request: %s", err.Error())
    }
    // req.Header.Add("Content-Type", "application/json")
    // req.Header.Add("Accept", "application/json")
    l.ServeHTTP(w, req)  // l在上面的某个地方定义了
    // 检查w.Code和w.Body
}

这段代码完全正常工作。现在我想要添加头部信息。所以我取消了注释,代码变成了:

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference

错误出现在这一行`l.ServeHTTP(w, req)`

有趣的是如果我只设置`Content-Type``Accept`其中一个测试就会通过但如果两个都设置测试就会失败出了什么问题

P.S. 我也尝试使用`req.Header.Set`但没有任何区别
这是我的处理程序的桩代码

```go
func (l myHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    // 检查有效性
    if !valid {
        http.Error(w, "Invalid Accept", http.StatusBadRequest)
        return
    }
    w.WriteHeader(http.StatusNoContent)
    return
}
英文:

I am trying to write tests for a simple rest application in go. So I write something like this:

func TestMyTestFunc(t *testing.T) {
	var w = httptest.NewRecorder()
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Errorf("Error creating request: %s", err.Error())
	}
	// req.Header.Add("Content-Type", "application/json")
	// req.Header.Add("Accept", "application/json")
    l.ServeHTTP(w, req)  // l is defined somewhere above
    // check for w.Code, w.Body
}

This works perfectly fine. Now I would like to add headers. So I add the commented header part and end up with:

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference

and the error is on this line: l.ServeHTTP(w, req).

Interesting part, that if I set only Content-Type or Accept, the test runs, but if I set both, it fails. What's wrong?

P.S. I also tried to use req.Header.Set, but with no difference.
Here is an stub for my handler:

func (l myHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    // check for validity
    if !valid {
       http.Error(w, "Invalid Accept", http.StatusBadRequest)
       return
    }
    w.WriteHeader(http.StatusNoContent)
	return
}

答案1

得分: 1

我认为你的HTTP服务器/处理程序实现中存在错误。我尝试重现了一下,并且它是有效的。

你可以在这里看到:
http://play.golang.org/p/n1YBl3OpbN

英文:

I think error in your http server/handler implementation. I tried to reproduce it and it worked.

You can see here:
http://play.golang.org/p/n1YBl3OpbN

huangapple
  • 本文由 发表于 2015年11月16日 16:13:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/33730877.html
匿名

发表评论

匿名网友

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

确定