如何在测试服务器中注入特定的IP地址?使用Golang编程语言。

huangapple go评论85阅读模式
英文:

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())
}

huangapple
  • 本文由 发表于 2014年6月30日 21:01:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/24490754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定