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

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

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

问题

我正在尝试测试一个根据IP地址提供信息的应用程序。然而,我找不到如何手动设置IP地址的方法。有什么想法吗?

  1. func TestClientData(t *testing.T) {
  2. URL := "http://home.com/hotel/lmx=100"
  3. req, err := http.NewRequest("GET", URL, nil)
  4. if err != nil {
  5. t.Fatal(err)
  6. }
  7. req.RemoveAddr := "0.0.0.0" ??
  8. w := httptest.NewRecorder()
  9. handler(w, req)
  10. b := w.Body.String()
  11. t.Log(b)
  12. }

我可以帮你翻译代码中的注释和字符串部分,但是代码本身不需要翻译。

英文:

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 ?

  1. func TestClientData(t *testing.T) {
  2. URL := "http://home.com/hotel/lmx=100"
  3. req, err := http.NewRequest("GET", URL, nil)
  4. if err != nil {
  5. t.Fatal(err)
  6. }
  7. req.RemoveAddr := "0.0.0.0" ??
  8. w := httptest.NewRecorder()
  9. handler(w, req)
  10. b := w.Body.String()
  11. t.Log(b)
  12. }

答案1

得分: 4

正确的代码行应该是:

  1. req.RemoteAddr = "0.0.0.0"

你不需要使用 :=。这样做是行不通的,因为你没有创建一个新的变量。

像这样(在 playground 上 http://play.golang.org/p/_6Z8wTrJsE):

  1. package main
  2. import (
  3. "io"
  4. "log"
  5. "net/http"
  6. "net/http/httptest"
  7. )
  8. func handler(w http.ResponseWriter, r *http.Request) {
  9. io.WriteString(w, "收到来自请求的信息:")
  10. io.WriteString(w, r.RemoteAddr)
  11. }
  12. func main() {
  13. url := "http://home.com/hotel/lmx=100"
  14. req, err := http.NewRequest("GET", url, nil)
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. // 这里不能使用 :=,因为 RemoteAddr 是一个结构体的字段,而不是一个变量
  19. req.RemoteAddr = "127.0.0.1"
  20. w := httptest.NewRecorder()
  21. handler(w, req)
  22. log.Print(w.Body.String())
  23. }
英文:

The correct line would be:

  1. 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):

  1. package main
  2. import (
  3. "io"
  4. "log"
  5. "net/http"
  6. "net/http/httptest"
  7. )
  8. func handler(w http.ResponseWriter, r *http.Request) {
  9. io.WriteString(w, "Got request from ")
  10. io.WriteString(w, r.RemoteAddr)
  11. }
  12. func main() {
  13. url := "http://home.com/hotel/lmx=100"
  14. req, err := http.NewRequest("GET", url, nil)
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. // can't use := here, because RemoteAddr is a field on a struct
  19. // and not a variable
  20. req.RemoteAddr = "127.0.0.1"
  21. w := httptest.NewRecorder()
  22. handler(w, req)
  23. log.Print(w.Body.String())
  24. }

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:

确定