github.com/treeverse/lakefs@v1.24.1-0.20240520134607-95648127bfb0/pkg/httputil/server.go (about)

     1  package httputil
     2  
     3  import (
     4  	"net"
     5  	"net/http"
     6  	"strings"
     7  )
     8  
     9  func HostOnly(hostname string) string {
    10  	if strings.Contains(hostname, ":") {
    11  		host, _, _ := net.SplitHostPort(hostname)
    12  		return host
    13  	}
    14  	return hostname
    15  }
    16  
    17  func HostsOnly(hostname []string) []string {
    18  	ret := make([]string, len(hostname))
    19  	for i := 0; i < len(hostname); i++ {
    20  		ret[i] = HostOnly(hostname[i])
    21  	}
    22  	return ret
    23  }
    24  
    25  func HostMatches(r *http.Request, hosts []string) bool {
    26  	host := HostOnly(r.Host)
    27  	vHost := HostsOnly(hosts)
    28  	for _, v := range vHost {
    29  		if v == host {
    30  			return true
    31  		}
    32  	}
    33  	return false
    34  }
    35  
    36  func HostSubdomainOf(r *http.Request, hosts []string) bool {
    37  	host := HostOnly(r.Host)
    38  	subVHost := HostsOnly(hosts)
    39  	for i := 0; i < len(subVHost); i++ {
    40  		subVHost[i] = "." + subVHost[i]
    41  	}
    42  	for _, subV := range subVHost {
    43  		if !strings.HasSuffix(host, subV) || len(host) < len(subV)+1 {
    44  			continue
    45  		}
    46  		dot := strings.IndexRune(host, '.')
    47  		if dot > -1 && dot < len(host)-len(subV) {
    48  			continue
    49  		}
    50  		return true // it is a direct sub-domain
    51  	}
    52  	return false
    53  }