connection_handler_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package socks
  2. import (
  3. "encoding/json"
  4. "io"
  5. "net"
  6. "net/http"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "golang.org/x/net/proxy"
  11. )
  12. type successResponse struct {
  13. Status string `json:"status"`
  14. }
  15. func sendSocksRequest(t *testing.T) []byte {
  16. dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:8086", nil, proxy.Direct)
  17. assert.NoError(t, err)
  18. httpTransport := &http.Transport{}
  19. httpClient := &http.Client{Transport: httpTransport}
  20. // set our socks5 as the dialer
  21. httpTransport.Dial = dialer.Dial
  22. req, err := http.NewRequest("GET", "http://127.0.0.1:8085", nil)
  23. assert.NoError(t, err)
  24. resp, err := httpClient.Do(req)
  25. assert.NoError(t, err)
  26. defer resp.Body.Close()
  27. b, err := io.ReadAll(resp.Body)
  28. assert.NoError(t, err)
  29. return b
  30. }
  31. func startTestServer(t *testing.T, httpHandler func(w http.ResponseWriter, r *http.Request)) {
  32. // create a socks server
  33. requestHandler := NewRequestHandler(NewNetDialer(), nil)
  34. socksServer := NewConnectionHandler(requestHandler)
  35. listener, err := net.Listen("tcp", "localhost:8086")
  36. assert.NoError(t, err)
  37. go func() {
  38. defer listener.Close()
  39. for {
  40. conn, _ := listener.Accept()
  41. go socksServer.Serve(conn)
  42. }
  43. }()
  44. // create an http server
  45. mux := http.NewServeMux()
  46. mux.HandleFunc("/", httpHandler)
  47. // start the servers
  48. go http.ListenAndServe("localhost:8085", mux)
  49. }
  50. func respondWithJSON(w http.ResponseWriter, v interface{}, status int) {
  51. data, _ := json.Marshal(v)
  52. w.Header().Set("Content-Type", "application/json")
  53. w.WriteHeader(status)
  54. w.Write(data)
  55. }
  56. func OkJSONResponseHandler(w http.ResponseWriter, r *http.Request) {
  57. resp := successResponse{
  58. Status: "ok",
  59. }
  60. respondWithJSON(w, resp, http.StatusOK)
  61. }
  62. func TestSocksConnection(t *testing.T) {
  63. startTestServer(t, OkJSONResponseHandler)
  64. time.Sleep(100 * time.Millisecond)
  65. b := sendSocksRequest(t)
  66. assert.True(t, len(b) > 0, "no data returned!")
  67. var resp successResponse
  68. json.Unmarshal(b, &resp)
  69. assert.True(t, resp.Status == "ok", "response didn't return ok")
  70. }