duandai0373 2017-10-11 08:58
浏览 1479
已采纳

Golang匹配域名通配符

I have hostnameWhitelist map

var hostnameWhitelist = map[string] bool { "test.mydomain.com":true, "test12.mydomaindev.com":true}

And the way I check if incoming request's hostname is allowed or not is -

    url, errURL := url.Parse("test.mydomain.com")
    if errURL != nil {
        fmt.Println("error during parsing URL")
        return false
    }
    fmt.Println("HOSTNAME = " + url.Hostname())

    if ok := hostnameWhitelist[url.Hostname()]; ok {
        fmt.Println("valid domain, allow access")
    } else {
        fmt.Println("NOT valid domain")
        return false
    }

While this works great, how do I do a wild card match like -

*.mydomain.com 
*.mydomaindev.com 

Both of these should pass.

While,

*.test.com
*.hello.com

should fail

  • 写回答

4条回答 默认 最新

  • drlhsfqoa350437979 2017-10-11 21:49
    关注

    Regex is the to go solution for your problem, map[string]bool may not work as expected as you are trying to match a regex with single value.

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        if matched, _ := regexp.MatchString(".*\\.?mydomain.*", "mydomaindev.com"); matched {
            fmt.Println("Valid domain")
        }
    }
    

    This would match all domain with pattern mydomain, so www.mydomain.com www.mydomaindev.com would match byt test.com and hello.com will fail

    Other handy string ops are,

    //This would match a.mydomain.com, b.mydomain.com etc.,
    if strings.HasSuffix(url1.Hostname(), ".mydomain.com") {
        fmt.Println("Valid domain allow access")
    }
    
    //To match anything with mydomain - like mydomain.com, mydomaindev.com
    if strings.Contains(url2.Hostname(), "mydomain.com") {
        fmt.Println("Valid domain allow access")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图