Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find implementation exposes default rules definition #229

Open
guliyevemil1 opened this issue Dec 10, 2019 · 1 comment
Open

Find implementation exposes default rules definition #229

guliyevemil1 opened this issue Dec 10, 2019 · 1 comment

Comments

@guliyevemil1
Copy link
Contributor

guliyevemil1 commented Dec 10, 2019

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
}
@weppos
Copy link
Owner

weppos commented Dec 19, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants