From fb628e9c62d2576aff3643d4ff30610a0a92c76f Mon Sep 17 00:00:00 2001 From: Dreamacro <305009791@qq.com> Date: Sun, 7 Jun 2020 17:25:51 +0800 Subject: [PATCH] Feature: add default hosts `localhost` --- component/trie/domain.go | 6 +++++- component/trie/domain_test.go | 3 +++ config/config.go | 6 ++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/component/trie/domain.go b/component/trie/domain.go index 5dc60553..e8dcf213 100644 --- a/component/trie/domain.go +++ b/component/trie/domain.go @@ -30,7 +30,11 @@ func validAndSplitDomain(domain string) ([]string, bool) { parts := strings.Split(domain, domainStep) if len(parts) == 1 { - return nil, false + if parts[0] == "" { + return nil, false + } + + return parts, true } for _, part := range parts[1:] { diff --git a/component/trie/domain_test.go b/component/trie/domain_test.go index ded5282b..38b347e1 100644 --- a/component/trie/domain_test.go +++ b/component/trie/domain_test.go @@ -14,6 +14,7 @@ func TestTrie_Basic(t *testing.T) { domains := []string{ "example.com", "google.com", + "localhost", } for _, domain := range domains { @@ -24,6 +25,8 @@ func TestTrie_Basic(t *testing.T) { assert.NotNil(t, node) assert.True(t, node.Data.(net.IP).Equal(localIP)) assert.NotNil(t, tree.Insert("", localIP)) + assert.Nil(t, tree.Search("")) + assert.NotNil(t, tree.Search("localhost")) } func TestTrie_Wildcard(t *testing.T) { diff --git a/config/config.go b/config/config.go index f1562bc2..f18d0369 100644 --- a/config/config.go +++ b/config/config.go @@ -418,6 +418,12 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) { func parseHosts(cfg *RawConfig) (*trie.DomainTrie, error) { tree := trie.New() + + // add default hosts + if err := tree.Insert("localhost", net.IP{127, 0, 0, 1}); err != nil { + println(err.Error()) + } + if len(cfg.Hosts) != 0 { for domain, ipStr := range cfg.Hosts { ip := net.ParseIP(ipStr)