You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

60 regels
1.8 KiB

  1. // Copyright 2015 Google Inc. All rights reserved.
  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 header
  15. import (
  16. "net"
  17. "net/http"
  18. "github.com/google/martian"
  19. )
  20. // NewForwardedModifier sets the X-Forwarded-For, X-Forwarded-Proto,
  21. // X-Forwarded-Host, and X-Forwarded-Url headers.
  22. //
  23. // If X-Forwarded-For is already present, the client IP is appended to
  24. // the existing value. X-Forwarded-Proto, X-Forwarded-Host, and
  25. // X-Forwarded-Url are preserved if already present.
  26. //
  27. // TODO: Support "Forwarded" header.
  28. // see: http://tools.ietf.org/html/rfc7239
  29. func NewForwardedModifier() martian.RequestModifier {
  30. return martian.RequestModifierFunc(
  31. func(req *http.Request) error {
  32. if v := req.Header.Get("X-Forwarded-Proto"); v == "" {
  33. req.Header.Set("X-Forwarded-Proto", req.URL.Scheme)
  34. }
  35. if v := req.Header.Get("X-Forwarded-Host"); v == "" {
  36. req.Header.Set("X-Forwarded-Host", req.Host)
  37. }
  38. if v := req.Header.Get("X-Forwarded-Url"); v == "" {
  39. req.Header.Set("X-Forwarded-Url", req.URL.String())
  40. }
  41. xff, _, err := net.SplitHostPort(req.RemoteAddr)
  42. if err != nil {
  43. xff = req.RemoteAddr
  44. }
  45. if v := req.Header.Get("X-Forwarded-For"); v != "" {
  46. xff = v + ", " + xff
  47. }
  48. req.Header.Set("X-Forwarded-For", xff)
  49. return nil
  50. })
  51. }