Inject headers into httptest.Recorder so echo context can see them in Golang

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

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")

huangapple
  • 本文由 发表于 2022年3月25日 20:15:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/71616836.html
匿名

发表评论

匿名网友

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

确定