doushi5913 2018-03-13 13:16
浏览 250
已采纳

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

In the code sample below, I use regex to extract the subdomain name from a given URL. This sample works, but I don't think I've done it correctly at the point where I compile the regex, mainly where I insert the 'virtualHost' variable. Any suggestions?

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
", result)
        return
    }

    fmt.Println("No subdomain detected")
}
  • 写回答

1条回答 默认 最新

  • doucezhu3570 2018-03-13 14:08
    关注

    The url package has a function parse that allows you to parse an URL. The parsed URL instance has a method Hostname which will return you the 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())
    }
    

    Output:

    login.localhost
    

    See https://play.golang.com/p/3R1TPyk8qck

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 adb连接不到手机是怎么回事?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目