1

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?

Woody1193
  • 7,252
  • 5
  • 40
  • 90
  • 1
    `Deprecated: HeaderMap exists for historical compatibility and should not be used. To access the headers returned by a handler, use the Response.Header map as returned by the Result method.` so `recorder.Result().Request.Header.Set("1", "2")` – Alex Efimov Mar 25 '22 at 12:40
  • @AlexEfimov That doesn't work though – Woody1193 Apr 15 '22 at 05:20
  • but why would you want to add headers to recorder and not request? The function that processes the request should add the header to the response (recorder). – Alex Efimov Apr 19 '22 at 06:39
  • @AlexEfimov I agree but for some reason my test doesn't work if I add the headers the way you specified. `test` should print a 304 for the status code but I'm getting a 0. – Woody1193 Apr 19 '22 at 12:04

1 Answers1

2

Instead of using HeaderMap() which is deprecated, you can use this:

request.Header().Set("Header-name", "Any header")