userspace_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2016 The etcd Authors
  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 tcpproxy
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "net/http/httptest"
  21. "net/url"
  22. "testing"
  23. )
  24. func TestUserspaceProxy(t *testing.T) {
  25. l, err := net.Listen("tcp", "127.0.0.1:0")
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. defer l.Close()
  30. want := "hello proxy"
  31. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  32. fmt.Fprint(w, want)
  33. }))
  34. defer ts.Close()
  35. u, err := url.Parse(ts.URL)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. var port uint16
  40. fmt.Sscanf(u.Port(), "%d", &port)
  41. p := TCPProxy{
  42. Listener: l,
  43. Endpoints: []*net.SRV{{Target: u.Hostname(), Port: port}},
  44. }
  45. go p.Run()
  46. defer p.Stop()
  47. u.Host = l.Addr().String()
  48. res, err := http.Get(u.String())
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. got, gerr := ioutil.ReadAll(res.Body)
  53. res.Body.Close()
  54. if gerr != nil {
  55. t.Fatal(gerr)
  56. }
  57. if string(got) != want {
  58. t.Errorf("got = %s, want %s", got, want)
  59. }
  60. }