簡體   English   中英

如何在測試服務器中注入特定的IP地址? Golang

[英]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)
}

正確的行是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM