github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/courier/transport_http/utils.go (about)

     1  package transport_http
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"net/http"
     7  	"strings"
     8  
     9  	"github.com/julienschmidt/httprouter"
    10  
    11  	"github.com/johnnyeven/libtools/courier/httpx"
    12  )
    13  
    14  func GetParams(path string, url string) (params httprouter.Params, err error) {
    15  	pathArr := strings.Split(httprouter.CleanPath(path), "/")
    16  	urlArr := strings.Split(httprouter.CleanPath(url), "/")
    17  
    18  	if len(pathArr) != len(urlArr) {
    19  		return nil, fmt.Errorf("url %s is not match path %s", url, path)
    20  	}
    21  
    22  	for i, p := range pathArr {
    23  		if strings.HasPrefix(p, ":") {
    24  			params = append(params, httprouter.Param{
    25  				Key:   p[1:],
    26  				Value: urlArr[i],
    27  			})
    28  		}
    29  	}
    30  
    31  	return params, nil
    32  }
    33  
    34  func GetClientIP(r *http.Request) string {
    35  	clientIP := r.Header.Get(httpx.HeaderForwardedFor)
    36  
    37  	if index := strings.IndexByte(clientIP, ','); index >= 0 {
    38  		clientIP = clientIP[0:index]
    39  	}
    40  	clientIP = strings.TrimSpace(clientIP)
    41  
    42  	if len(clientIP) > 0 {
    43  		return clientIP
    44  	}
    45  
    46  	clientIP = strings.TrimSpace(r.Header.Get(httpx.HeaderRealIP))
    47  
    48  	if len(clientIP) > 0 {
    49  		return clientIP
    50  	}
    51  
    52  	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
    53  		return ip
    54  	}
    55  
    56  	return ""
    57  }