dongqian3750 2014-06-30 13:01
浏览 53

如何在测试服务器中注入特定的IP地址? Golang

I'm trying to test an application which provides information based on ip address. However I can't find how to set the Ip address manually . Any idea ?

func TestClientData(t *testing.T) {

    URL := "http://home.com/hotel/lmx=100"

    req, err := http.NewRequest("GET", URL, nil)
    if err != nil {
        t.Fatal(err)
    }
    req.RemoveAddr := "0.0.0.0" ??

    w := httptest.NewRecorder()
    handler(w, req)

    b := w.Body.String()
    t.Log(b)
}
  • 写回答

1条回答 默认 最新

  • douyong8801 2014-06-30 19:12
    关注

    The correct line would be:

    req.RemoteAddr = "0.0.0.0"
    

    You don't need the :=. It won't work because you don't create a new variable.

    Like this (on playground http://play.golang.org/p/_6Z8wTrJsE):

    package main
    
    import (
        "io"
        "log"
        "net/http"
        "net/http/httptest"
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
        io.WriteString(w, "Got request from ")
        io.WriteString(w, r.RemoteAddr)
    }
    
    func main() {
        url := "http://home.com/hotel/lmx=100"
    
        req, err := http.NewRequest("GET", url, nil)
        if err != nil {
            log.Fatal(err)
        }
    
        // can't use := here, because RemoteAddr is a field on a struct
        // and not a variable
        req.RemoteAddr = "127.0.0.1"
    
        w := httptest.NewRecorder()
        handler(w, req)
    
        log.Print(w.Body.String())
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大