github.com/rudderlabs/rudder-go-kit@v0.30.0/httputil/client.go (about)

     1  package httputil
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  	"strings"
     7  )
     8  
     9  const (
    10  	headerXForwardedFor = "X-Forwarded-For"
    11  )
    12  
    13  // CloseResponse closes the response's body. But reads at least some of the body so if it's
    14  // small the underlying TCP connection will be re-used. No need to check for errors: if it
    15  // fails, the Transport won't reuse it anyway.
    16  func CloseResponse(resp *http.Response) {
    17  	if resp != nil && resp.Body != nil {
    18  		const maxBodySlurpSize = 2 << 10 // 2KB
    19  		_, _ = io.CopyN(io.Discard, resp.Body, maxBodySlurpSize)
    20  		resp.Body.Close()
    21  	}
    22  }
    23  
    24  func GetRequestIP(req *http.Request) string {
    25  	addresses := strings.Split(req.Header.Get(headerXForwardedFor), ",")
    26  	if addresses[0] == "" {
    27  		splits := strings.Split(req.RemoteAddr, ":")
    28  		return strings.Join(splits[:len(splits)-1], ":") // When there is no load-balancer
    29  	}
    30  
    31  	return strings.ReplaceAll(addresses[0], " ", "")
    32  }