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