英文:
How can I inject a specific IP address in the test server ? Golang
问题
我正在尝试测试一个根据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)
}
我可以帮你翻译代码中的注释和字符串部分,但是代码本身不需要翻译。
英文:
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
得分: 4
正确的代码行应该是:
req.RemoteAddr = "0.0.0.0"
你不需要使用 :=。这样做是行不通的,因为你没有创建一个新的变量。
像这样(在 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, "收到来自请求的信息:")
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)
}
// 这里不能使用 :=,因为 RemoteAddr 是一个结构体的字段,而不是一个变量
req.RemoteAddr = "127.0.0.1"
w := httptest.NewRecorder()
handler(w, req)
log.Print(w.Body.String())
}
英文:
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())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论