userspace_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. p := TCPProxy{
  40. Listener: l,
  41. Endpoints: []string{u.Host},
  42. }
  43. go p.Run()
  44. defer p.Stop()
  45. u.Host = l.Addr().String()
  46. res, err := http.Get(u.String())
  47. if err != nil {
  48. t.Fatal(err)
  49. }
  50. got, gerr := ioutil.ReadAll(res.Body)
  51. res.Body.Close()
  52. if gerr != nil {
  53. t.Fatal(gerr)
  54. }
  55. if string(got) != want {
  56. t.Errorf("got = %s, want %s", got, want)
  57. }
  58. }