donglinxin8765 2019-07-30 15:03
浏览 318

如何测试http.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.

  • 写回答

1条回答 默认 最新

  • dqn48247 2019-07-30 15:58
    关注

    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()
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试