publicsuffix-go icon indicating copy to clipboard operation
publicsuffix-go copied to clipboard

Find implementation exposes default rules definition

Open guliyevemil1 opened this issue 5 years ago • 1 comments

Because Find returns pointers, it allows the user of the library to modify default definitions. It's true that it shouldn't be done to begin with, but it would be good to protect against it.

// Find and returns the most appropriate rule for the domain name.
func (l *List) Find(name string, options *FindOptions) *Rule {
	if options == nil {
		options = DefaultFindOptions
	}

	part := name
	for {
		rule, ok := l.rules[part]

		if ok && rule.Match(name) && !(options.IgnorePrivate && rule.Private) {
			return rule
		}

		i := strings.IndexRune(part, '.')
		if i < 0 {
			return options.DefaultRule
		}

		part = part[i+1:]
	}

	return nil
}

We can rewrite it as such:

// Find and returns the most appropriate rule for the domain name.
func (l *List) Find(name string, options *FindOptions) *Rule {
	if options == nil {
		options = DefaultFindOptions
	}

	part := name
	var out Rule
	for {
		rule, ok := l.rules[part]

		if ok && rule.Match(name) && !(options.IgnorePrivate && rule.Private) {
			out = *rule
			return &out
		}

		i := strings.IndexRune(part, '.')
		if i < 0 {
			out = *options.DefaultRule
			return &out
		}

		part = part[i+1:]
	}

	return nil
}

guliyevemil1 avatar Dec 10 '19 22:12 guliyevemil1

Thanks @guliyevemil1 , I agree we should return a copy. Do you mind to open a PR? It would be nice to have a test as well.

weppos avatar Dec 19 '19 14:12 weppos