transport.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 transport
  15. import (
  16. "net"
  17. "net/http"
  18. "strings"
  19. "time"
  20. )
  21. type unixTransport struct{ *http.Transport }
  22. func NewTransport(info TLSInfo, dialtimeoutd time.Duration) (*http.Transport, error) {
  23. cfg, err := info.ClientConfig()
  24. if err != nil {
  25. return nil, err
  26. }
  27. t := &http.Transport{
  28. Proxy: http.ProxyFromEnvironment,
  29. Dial: (&net.Dialer{
  30. Timeout: dialtimeoutd,
  31. // value taken from http.DefaultTransport
  32. KeepAlive: 30 * time.Second,
  33. }).Dial,
  34. // value taken from http.DefaultTransport
  35. TLSHandshakeTimeout: 10 * time.Second,
  36. TLSClientConfig: cfg,
  37. }
  38. dialer := (&net.Dialer{
  39. Timeout: dialtimeoutd,
  40. KeepAlive: 30 * time.Second,
  41. })
  42. dial := func(net, addr string) (net.Conn, error) {
  43. return dialer.Dial("unix", addr)
  44. }
  45. tu := &http.Transport{
  46. Proxy: http.ProxyFromEnvironment,
  47. Dial: dial,
  48. TLSHandshakeTimeout: 10 * time.Second,
  49. TLSClientConfig: cfg,
  50. }
  51. ut := &unixTransport{tu}
  52. t.RegisterProtocol("unix", ut)
  53. t.RegisterProtocol("unixs", ut)
  54. return t, nil
  55. }
  56. func (urt *unixTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  57. url := *req.URL
  58. req.URL = &url
  59. req.URL.Scheme = strings.Replace(req.URL.Scheme, "unix", "http", 1)
  60. return urt.Transport.RoundTrip(req)
  61. }