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.

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

报告相同问题?

悬赏问题

  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 怎么改成输入一个要删除的数后现实剩余的数再输入一个删除的数再现实剩余的数用yes表示继续no结束程序
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取