使用Golang中的regexp从URL中提取子域

时间:2018-03-13 13:16:27

标签: regex go subdomain

在下面的代码示例中,我使用正则表达式从给定的URL中提取子域名。这个示例有效,但我认为我在编译正则表达式时没有正确完成,主要是我插入'virtualHost'变量。有什么建议吗?

Google Analytics for Firebase

2 个答案:

答案 0 :(得分:4)

url包有一个函数parse,允许您解析URL。解析后的URL实例有一个方法Hostname,它将返回主机名。

package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {
    u, err := url.Parse("http://login.localhost:3000")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(u.Hostname())
}

输出:

login.localhost

请参阅https://play.golang.com/p/3R1TPyk8qck

答案 1 :(得分:0)

这是我用过的


func getSubdomain(r *http.Request) string {
    //The Host that the user queried.
    host := r.URL.Host
    host = strings.TrimSpace(host)
    //Figure out if a subdomain exists in the host given.
    hostParts := strings.Split(host, ".")

    fmt.Println("host parts",hostParts)

    lengthOfHostParts := len(hostParts)

    // scenarios
    // A. site.com  -> length : 2
    // B. www.site.com -> length : 3
    // C. www.hello.site.com -> length : 4

    if lengthOfHostParts == 4 {
        return strings.Join([]string{hostParts[1]},"") // scenario C
    }
    
    if lengthOfHostParts == 3 { // scenario B with a check
        subdomain := strings.Join([]string{hostParts[0]},"")
        
        if subdomain == "www" {
            return ""
        } else {
            return subdomain
        }
    }

    return "" // scenario A
}