Sam Costley
Sam Costley

Reputation: 39

How to test that http.Redirect uses correct redirect URI?

I have a Go backend that uses the net/http package. I have an endpoint that is meant to redirect using http.Redirect to a provided redirect URI with some generated GET parameters. I simply want to test using net/http/httptest and testing that my endpoint is redirecting to the proper URL.

I have executed the request using ServeHTTP and can verify that it does return the correct status code (303 in this case). I then tried accessing the Request URL to find the most recent URL that was accessed (what I assumed to be the redirect URL), but I was unable to access this variable.

req, _ := http.NewRequest("GET", "https://www.urlthatredirects.com"), nil)
w := httptest.NewRecorder()
MyRouterMux().ServeHTTP(w, req)
resp := w.Result()

redirectUrl := resp.Request.URL

In this example, I would expect the redirectUrl variable to contain the URL that was redirected to, but instead I receive [signal SIGSEGV: segmentation violation ...]

Any idea what could be going on? I know from manual testing that the endpoint works as intended, but I simply need to prove through the tests that it does.

Upvotes: 1

Views: 1071

Answers (1)

Sam Costley
Sam Costley

Reputation: 39

Thanks to the comments, I have found that I was looking for the redirect url in the wrong place. The correct way to evaluate this is to capture the url from the Location header.

w := httptest.NewRecorder()
MyRouterMux().ServeHTTP(w, req)
resp := w.Result()

redirectUrl, err := resp.Location()

Upvotes: 1

Related Questions