douyu7879 2015-04-20 09:05
浏览 166
已采纳

测试HTTP请求时出现Nil解除引用错误

I am trying to test a HTTP request in my Go library. Object which makes the call accepts a HTTP client object via dependency injection so in my test I am mocking the HTTP client like this:

func TestMyObject(t *testing.T) {
    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(200)
        w.Header().Set("Content-Type", "application/json")
        fmt.Fprintln(w, mockJSONResponse)
    }))
    defer server.Close()

    // Make a transport that reroutes all traffic to the example server
    transport := &http.Transport{
        Proxy: func(req *http.Request) (*url.URL, error) {
            return url.Parse(server.URL)
        },
    }

    // Make a http.Client with the transport
    httpClient := &http.Client{Transport: transport}

    // I am passing the httpClient to my object
}

Here is how the HTTP request is made within my object:

// Make - makes a prepared HTTP request
func (ir *MyObject) Make() *http.Response {
    if ir.Err != nil {
        return nil
    }

    ir.resp, ir.Err = ir.Client.Do(ir.req)

    runtime.SetFinalizer(ir, func(ir *MyObject) {
        ir.resp.Body.Close()
    })

    ir.logReqRes()
    ir.checkErrorResponse()

    return ir.resp
}

I am getting nil pointer dereference error though:

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference

In this function (I am trying to log the response):

// Logs request and response
func (ir *MyObject) logReqRes() {
    log.Print("AAAAAAA")
    log.Print(ir.resp)
    log.Print("AAAAAAA")
    if reqInfo, err := httputil.DumpRequest(ir.req, true); err == nil {
        log.Print("Logging request:")
        log.Print(string(reqInfo))
    }
    if respInfo, err := httputil.DumpResponse(ir.resp, true); err == nil {
        log.Print("Logging response:")
        log.Print(string(respInfo))
    }
}

As you can see, ir.resp is nil for some reason. Any ideas?

  • 写回答

1条回答 默认 最新

  • doumeng3080 2015-04-20 09:44
    关注

    Ok. I found an issue. Better logging of errors actually showed that my mistake was very simple.

    I was passing this as a URL to mocked HTTP client:

    host/api/v1/tokens/
    

    Which was resulting in this error:

    Post host/api/v1/tokens/: unsupported protocol scheme
    

    Apparently the URL must include a proper HTTP scheme (http://) even when you are using a test server.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料