You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Go语言模拟HTTP响应器的调用次数统计结果不符合预期

问题原因

该问题由Go语言的值传递机制导致:

  • 你定义的mockHTTPResponder接收的是stringProducer值类型参数,调用mockHTTPResponder(producer)时会完整拷贝一份main函数里的producer实例,函数内使用的是拷贝得到的副本。
  • 后续HTTP请求触发GetNext()方法时,修改的是副本的callCount字段,main函数中原始的producer实例完全没有被改动,因此最终校验时callCount值仍为0,触发panic。

修复方案

只需要调整两处代码,让mock函数和main函数共用同一个stringProducer实例即可:

  1. 修改mockHTTPResponder的参数类型为*stringProducer指针类型,避免值拷贝
func mockHTTPResponder(producer *stringProducer) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(producer.GetNext()))
    })
}
  1. 调用mockHTTPResponder时传入producer的指针
srv := httptest.NewServer(mockHTTPResponder(&producer))

修改后HTTP请求触发的callCount递增会直接作用在main函数的原始producer实例上,校验逻辑可以正常通过。

内容的提问来源于stack exchange,提问作者Saqib Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:06:01