roundtripper_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package http
  17. import (
  18. "io/ioutil"
  19. "net"
  20. "net/http"
  21. "net/http/httptest"
  22. "strings"
  23. "testing"
  24. "time"
  25. )
  26. func TestRoundTripper(t *testing.T) {
  27. serveMux := http.NewServeMux()
  28. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  29. if r.Method == "GET" {
  30. w.Header().Set("Content-Type", "text/plain")
  31. http.ServeContent(w, r, "", time.Unix(0, 0), strings.NewReader(r.RequestURI))
  32. } else {
  33. http.Error(w, "Method "+r.Method+" is not supported.", http.StatusMethodNotAllowed)
  34. }
  35. })
  36. srv := httptest.NewServer(serveMux)
  37. defer srv.Close()
  38. host, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
  39. rt := &RoundTripper{Host: host, Port: port}
  40. trans := &http.Transport{}
  41. trans.RegisterProtocol("bzz", rt)
  42. client := &http.Client{Transport: trans}
  43. resp, err := client.Get("bzz://test.com/path")
  44. if err != nil {
  45. t.Errorf("expected no error, got %v", err)
  46. return
  47. }
  48. defer func() {
  49. if resp != nil {
  50. resp.Body.Close()
  51. }
  52. }()
  53. content, err := ioutil.ReadAll(resp.Body)
  54. if err != nil {
  55. t.Errorf("expected no error, got %v", err)
  56. return
  57. }
  58. if string(content) != "/HTTP/1.1:/test.com/path" {
  59. t.Errorf("incorrect response from http server: expected '%v', got '%v'", "/HTTP/1.1:/test.com/path", string(content))
  60. }
  61. }