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

Kar*_*sen 0 regex subdomain go

在下面的代码示例中,我使用正则表达式从给定的URL中提取子域名。该示例有效,但我认为我在编译正则表达式时(主要是在插入“ virtualHost”变量的地方)未正确完成操作。有什么建议么?

package main

import (
    "fmt"
    "regexp"
)

var (
    virtualHost string
    domainRegex *regexp.Regexp
)

func extractSubdomain(host string) string {
    matches := domainRegex.FindStringSubmatch(host)
    if matches != nil && len(matches) > 1 {
        return matches[1]
    }
    return ""
}

func init() {
    // virtualHost = os.GetEnv("VIRTUAL_HOST")
    virtualHost = "login.localhost:3000"

    domainRegex = regexp.MustCompile(`^(?:https?://)?([-a-z0-9]+)(?:\.` + virtualHost + `)*$`)
}

func main() {
    // host := req.host
    host := "http://acme.login.localhost:3000"

    if result := extractSubdomain(host); result != "" {
        fmt.Printf("Subdomain detected: %s\n", result)
        return
    }

    fmt.Println("No subdomain detected")
}
Run Code Online (Sandbox Code Playgroud)

小智 5

url包装具有的功能parse,允许您解析URL。解析的URL实例具有Hostname将返回您的主机名的方法。

包主

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())
}
Run Code Online (Sandbox Code Playgroud)

输出:

login.localhost
Run Code Online (Sandbox Code Playgroud)

参见https://play.golang.com/p/3R1TPyk8qck

  • 我不知道为什么这被标记为答案。它为您提供完整的主机名,而不是所询问的子域。这不是答案。 (4认同)