Files
authorizer/server/utils/urls.go

76 lines
1.4 KiB
Go
Raw Normal View History

package utils
import (
2022-01-31 11:35:24 +05:30
"log"
"net/url"
"strings"
2022-01-31 11:35:24 +05:30
"github.com/gin-gonic/gin"
)
2022-01-31 11:35:24 +05:30
// GetHost returns hostname from request context
func GetHost(c *gin.Context) string {
2022-01-31 14:30:13 +05:30
scheme := c.Request.Header.Get("X-Forwarded-Proto")
if scheme != "https" {
scheme = "http"
2022-01-31 11:35:24 +05:30
}
2022-01-31 14:30:13 +05:30
host := c.Request.Host
log.Println("=> host:", scheme+"://"+host)
return scheme + "://" + host
2022-01-31 11:35:24 +05:30
}
// GetHostName function returns hostname and port
func GetHostParts(uri string) (string, string) {
tempURI := uri
if !strings.HasPrefix(tempURI, "http://") && !strings.HasPrefix(tempURI, "https://") {
tempURI = "https://" + tempURI
}
u, err := url.Parse(tempURI)
if err != nil {
return "localhost", "8080"
}
host := u.Hostname()
port := u.Port()
return host, port
}
// GetDomainName function to get domain name
func GetDomainName(uri string) string {
tempURI := uri
if !strings.HasPrefix(tempURI, "http://") && !strings.HasPrefix(tempURI, "https://") {
tempURI = "https://" + tempURI
}
u, err := url.Parse(tempURI)
if err != nil {
return `localhost`
}
2021-07-22 05:22:53 +05:30
host := u.Hostname()
2021-07-28 23:53:54 +05:30
// code to get root domain in case of sub-domains
hostParts := strings.Split(host, ".")
hostPartsLen := len(hostParts)
if hostPartsLen == 1 {
return host
}
if hostPartsLen == 2 {
if hostParts[0] == "www" {
return hostParts[1]
} else {
return host
}
}
if hostPartsLen > 2 {
return strings.Join(hostParts[hostPartsLen-2:], ".")
}
2021-07-22 05:22:53 +05:30
return host
}