reverse.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package proxy
  14. import (
  15. "io"
  16. "log"
  17. "net"
  18. "net/http"
  19. "net/url"
  20. "strings"
  21. )
  22. // Hop-by-hop headers. These are removed when sent to the backend.
  23. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  24. // This list of headers borrowed from stdlib httputil.ReverseProxy
  25. var singleHopHeaders = []string{
  26. "Connection",
  27. "Keep-Alive",
  28. "Proxy-Authenticate",
  29. "Proxy-Authorization",
  30. "Te", // canonicalized version of "TE"
  31. "Trailers",
  32. "Transfer-Encoding",
  33. "Upgrade",
  34. }
  35. func removeSingleHopHeaders(hdrs *http.Header) {
  36. for _, h := range singleHopHeaders {
  37. hdrs.Del(h)
  38. }
  39. }
  40. type reverseProxy struct {
  41. director *director
  42. transport http.RoundTripper
  43. }
  44. func (p *reverseProxy) ServeHTTP(rw http.ResponseWriter, clientreq *http.Request) {
  45. proxyreq := new(http.Request)
  46. *proxyreq = *clientreq
  47. // deep-copy the headers, as these will be modified below
  48. proxyreq.Header = make(http.Header)
  49. copyHeader(proxyreq.Header, clientreq.Header)
  50. normalizeRequest(proxyreq)
  51. removeSingleHopHeaders(&proxyreq.Header)
  52. maybeSetForwardedFor(proxyreq)
  53. endpoints := p.director.endpoints()
  54. if len(endpoints) == 0 {
  55. log.Printf("proxy: zero endpoints currently available")
  56. rw.WriteHeader(http.StatusServiceUnavailable)
  57. return
  58. }
  59. var res *http.Response
  60. var err error
  61. for _, ep := range endpoints {
  62. redirectRequest(proxyreq, ep.URL)
  63. res, err = p.transport.RoundTrip(proxyreq)
  64. if err != nil {
  65. log.Printf("proxy: failed to direct request to %s: %v", ep.URL.String(), err)
  66. ep.Failed()
  67. continue
  68. }
  69. break
  70. }
  71. if res == nil {
  72. log.Printf("proxy: unable to get response from %d endpoint(s)", len(endpoints))
  73. rw.WriteHeader(http.StatusBadGateway)
  74. return
  75. }
  76. defer res.Body.Close()
  77. removeSingleHopHeaders(&res.Header)
  78. copyHeader(rw.Header(), res.Header)
  79. rw.WriteHeader(res.StatusCode)
  80. io.Copy(rw, res.Body)
  81. }
  82. func copyHeader(dst, src http.Header) {
  83. for k, vv := range src {
  84. for _, v := range vv {
  85. dst.Add(k, v)
  86. }
  87. }
  88. }
  89. func redirectRequest(req *http.Request, loc url.URL) {
  90. req.URL.Scheme = loc.Scheme
  91. req.URL.Host = loc.Host
  92. }
  93. func normalizeRequest(req *http.Request) {
  94. req.Proto = "HTTP/1.1"
  95. req.ProtoMajor = 1
  96. req.ProtoMinor = 1
  97. req.Close = false
  98. }
  99. func maybeSetForwardedFor(req *http.Request) {
  100. clientIP, _, err := net.SplitHostPort(req.RemoteAddr)
  101. if err != nil {
  102. return
  103. }
  104. // If we aren't the first proxy retain prior
  105. // X-Forwarded-For information as a comma+space
  106. // separated list and fold multiple headers into one.
  107. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  108. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  109. }
  110. req.Header.Set("X-Forwarded-For", clientIP)
  111. }