github.com/blend/go-sdk@v1.20220411.3/webutil/get_remoteaddr.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package webutil
     9  
    10  // github:codeowner @blend/seceng
    11  
    12  import (
    13  	"net"
    14  	"net/http"
    15  )
    16  
    17  // GetRemoteAddr gets the origin/client ip for a request.
    18  // X-FORWARDED-FOR is checked. If multiple IPs are included the first one is returned
    19  // X-REAL-IP is checked. If multiple IPs are included the last one is returned
    20  // Finally r.RemoteAddr is used
    21  // Only benevolent services will allow access to the real IP.
    22  func GetRemoteAddr(r *http.Request) string {
    23  	if r == nil {
    24  		return ""
    25  	}
    26  	tryHeader := func(key string) (string, bool) {
    27  		return HeaderLastValue(r.Header, key)
    28  	}
    29  	for _, header := range []string{HeaderXForwardedFor, HeaderXRealIP} {
    30  		if headerVal, ok := tryHeader(header); ok {
    31  			return headerVal
    32  		}
    33  	}
    34  	ip, _, _ := net.SplitHostPort(r.RemoteAddr)
    35  	return ip
    36  }