英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论