From befbee49548e21ae04c8411e34b28b21e5d52788 Mon Sep 17 00:00:00 2001 From: Peter Krejci Date: Fri, 10 Mar 2017 16:58:00 +0100 Subject: [PATCH] add support for wildcards in allowed_hosts, add tests for allowsHost() --- server.go | 13 +++++++++++++ server_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/server.go b/server.go index 9ceac110..4abd0adc 100644 --- a/server.go +++ b/server.go @@ -16,6 +16,7 @@ import ( "github.com/flashmob/go-guerrilla/envelope" "github.com/flashmob/go-guerrilla/log" "github.com/flashmob/go-guerrilla/response" + "path/filepath" ) const ( @@ -244,6 +245,18 @@ func (server *server) allowsHost(host string) bool { if _, ok := server.hosts.table[strings.ToLower(host)]; ok { return true } + if _, ok := server.hosts.table["*"]; ok { + return true + } + for pattern := range server.hosts.table { + matched, err := filepath.Match(pattern, host) + if err != nil { + return false + } + if matched { + return true + } + } return false } diff --git a/server_test.go b/server_test.go index 283522b4..56bacbd3 100644 --- a/server_test.go +++ b/server_test.go @@ -90,6 +90,43 @@ func TestHandleClient(t *testing.T) { wg.Wait() // wait for handleClient to exit } +func TestAllowsHosts(t *testing.T) { + s := server{} + allowedHosts := []string{ + "spam4.me", + "grr.la", + "newhost.com", + "example.*", + "*.test", + "wild*.card", + "multiple*wild*cards.*", + } + s.setAllowedHosts(allowedHosts) + + testTable := map[string]bool{ + "spam4.me": true, + "dont.match": false, + "example.com": true, + "another.example.com": false, + "anything.test": true, + "wild.card": true, + "wild.card.com": false, + "multipleXwildXcards.com": true, + } + + for host, allows := range testTable { + if res := s.allowsHost(host); res != allows { + t.Error(host, ": expected", allows, "but got", res) + } + } + + // only wildcard - should match anything + s.setAllowedHosts([]string{"*"}) + if !s.allowsHost("match.me") { + t.Error("match.me: expected true but got false") + } +} + // TODO // - test github issue #44 and #42 // - test other commands