英文:
Inject headers into httptest.Recorder so echo context can see them in Golang
问题
我有一些将标头注入到 Echo 中的测试,代码如下:
func test() {
request := httptest.NewRequest(http.MethodGet, "/", http.NoBody)
recorder := httptest.NewRecorder()
recorder.HeaderMap.Add("If-None-Match", "\"d41d8cd98f00b204e9800998ecf8427e\"")
context := inst.NewContext(request, recorder)
testFunc(context)
fmt.Printf("Status: %d", context.Response().Status)
}
func testFunc(ctx echo.Context) {
ifNoneMatch := ctx.Response().Header().Get(headers.IfNoneMatch)
if !util.IsEmpty(ifNoneMatch) && etag == ifNoneMatch {
ctx.Response().WriteHeader(304)
}
}
我的当前解决方案有效,但由于 HeaderMap
已被弃用,我正在尝试找到更好的方法来实现这一点。我尝试通过在 Result
中注入标头来实现,例如 Result().Header.Add("If-None-Match", "\"d41d8cd98f00b204e9800998ecf8427e\"")
,但在调用 context.Response().Header()
时似乎没有显示出来。有没有办法可以做到这一点?
英文:
I have some tests that inject headers into Echo like this:
func test() {
request := httptest.NewRequest(http.MethodGet, "/", http.NoBody)
recorder := httptest.NewRecorder()
recorder.HeaderMap.Add("If-None-Match", "\"d41d8cd98f00b204e9800998ecf8427e\"")
context := inst.NewContext(request, recorder)
testFunc(context)
fmt.Printf("Status: %d", context.Response().Status)
}
func testFunc(ctx echo.Context) {
ifNoneMatch := ctx.Response().Header().Get(headers.IfNoneMatch)
if !util.IsEmpty(ifNoneMatch) && etag == ifNoneMatch {
ctx.Response().WriteHeader(304)
}
}
My current solution works but, as HeaderMap
is deprecated, I'm trying to find a better way to do this. I've tried injecting the header into Result
by doing Result().Header.Add("If-None-Match", "\"d41d8cd98f00b204e9800998ecf8427e\"")
but it doesn't seem to show up when calling context.Response().Header()
. Is there any way to do this?
答案1
得分: 2
不要使用已弃用的HeaderMap(),可以使用以下代码:
request.Header().Set("Header-name", "Any header")
英文:
Instead of using HeaderMap() which is deprecated, you can use this:
request.Header().Set("Header-name", "Any header")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论