http_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package netutils2
  15. import (
  16. "net/http"
  17. "testing"
  18. )
  19. func TestGetHttpRequestIp(t *testing.T) {
  20. cases := []struct {
  21. request *http.Request
  22. want string
  23. }{
  24. {
  25. request: &http.Request{
  26. Header: map[string][]string{
  27. "X-Forwarded-For": []string{
  28. "10.168.26.232",
  29. },
  30. },
  31. RemoteAddr: "10.168.26.2:32322",
  32. },
  33. want: "10.168.26.232",
  34. },
  35. {
  36. request: &http.Request{
  37. RemoteAddr: "192.168.222.23:35533",
  38. },
  39. want: "192.168.222.23",
  40. },
  41. {
  42. request: &http.Request{
  43. Header: map[string][]string{
  44. "X-Real-Ip": []string{
  45. "10.40.23.3",
  46. },
  47. },
  48. RemoteAddr: "192.168.222.23:34343",
  49. },
  50. want: "10.40.23.3",
  51. },
  52. {
  53. request: &http.Request{
  54. Header: map[string][]string{
  55. "X-Real-Ip": []string{
  56. "10.40.23.3",
  57. },
  58. "X-Forwarded-For": []string{
  59. "211.25.23.2, 10.34.3.1, 192.168.222.3",
  60. },
  61. },
  62. RemoteAddr: "192.168.222.23:34343",
  63. },
  64. want: "211.25.23.2",
  65. },
  66. }
  67. for _, c := range cases {
  68. got := GetHttpRequestIp(c.request)
  69. if got != c.want {
  70. t.Errorf("got: %s want: %s", got, c.want)
  71. }
  72. }
  73. }