Files
routedns/blocklistloader-local.go
2023-03-26 12:45:54 +02:00

56 lines
1.3 KiB
Go

package rdns
import (
"bufio"
"os"
)
// FileLoader reads blocklist rules from a local file. Used to refresh blocklists
// from a file on the local machine.
type FileLoader struct {
filename string
opt FileLoaderOptions
lastSuccess []string
}
// FileLoaderOptions holds options for file blocklist loaders.
type FileLoaderOptions struct {
// Don't fail when trying to load the list
AllowFailure bool
}
var _ BlocklistLoader = &FileLoader{}
func NewFileLoader(filename string, opt FileLoaderOptions) *FileLoader {
return &FileLoader{filename, opt, nil}
}
func (l *FileLoader) Load() (rules []string, err error) {
log := Log.WithField("file", l.filename)
log.Trace("loading blocklist")
// If AllowFailure is enabled, return the last successfully loaded list
// and nil
defer func() {
if err != nil && l.opt.AllowFailure {
log.WithError(err).Warn("failed to load blocklist, continuing with previous ruleset")
rules = l.lastSuccess
err = nil
} else {
l.lastSuccess = rules
}
}()
f, err := os.Open(l.filename)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
rules = append(rules, scanner.Text())
}
log.Trace("completed loading blocklist")
return rules, scanner.Err()
}