Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject a specific IP address in the test server ? Golang

Tags:

go

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)
}
like image 310
hey Avatar asked Oct 28 '25 20:10

hey


1 Answers

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())
}
like image 84
nussjustin Avatar answered Oct 30 '25 11:10

nussjustin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!