github.com/google/martian/v3@v3.3.3/header/forwarded_modifier.go (about)

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