Search code examples
regexgosubdomainwildcard

Golang match domain names wild card


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


Solution

  • 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")
    }