我试图测试一个基于ip地址提供信息的应用程序。但是,我无法手动设置如何设置IP地址。任何的想法 ?
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)
}
答案 0 :(得分:3)
正确的行是:
req.RemoteAddr = "0.0.0.0"
你不需要:=。它不会起作用,因为你没有创建一个新的变量。
像这样(在游乐场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())
}