Skip to content

Commit

Permalink
Merge pull request #3758 from johngmyers/serialize
Browse files Browse the repository at this point in the history
Add serialization/deserialization support to DomainFilter
  • Loading branch information
k8s-ci-robot authored Jul 20, 2023
2 parents 22da9f2 + 29a6372 commit 659c4fb
Show file tree
Hide file tree
Showing 2 changed files with 411 additions and 33 deletions.
67 changes: 67 additions & 0 deletions endpoint/domain_filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ limitations under the License.
package endpoint

import (
"encoding/json"
"errors"
"fmt"
"regexp"
"sort"
"strings"
)

Expand Down Expand Up @@ -52,6 +56,14 @@ type DomainFilter struct {
regexExclusion *regexp.Regexp
}

// domainFilterSerde is a helper type for serializing and deserializing DomainFilter.
type domainFilterSerde struct {
Include []string `json:"include,omitempty"`
Exclude []string `json:"exclude,omitempty"`
RegexInclude string `json:"regexInclude,omitempty"`
RegexExclude string `json:"regexExclude,omitempty"`
}

// prepareFilters provides consistent trimming for filters/exclude params
func prepareFilters(filters []string) []string {
var fs []string
Expand Down Expand Up @@ -159,3 +171,58 @@ func (df DomainFilter) IsConfigured() bool {
}
return len(df.Filters) > 0 || len(df.exclude) > 0
}

func (df DomainFilter) MarshalJSON() ([]byte, error) {
if df.regex != nil || df.regexExclusion != nil {
var include, exclude string
if df.regex != nil {
include = df.regex.String()
}
if df.regexExclusion != nil {
exclude = df.regexExclusion.String()
}
return json.Marshal(domainFilterSerde{
RegexInclude: include,
RegexExclude: exclude,
})
}
sort.Strings(df.Filters)
sort.Strings(df.exclude)
return json.Marshal(domainFilterSerde{
Include: df.Filters,
Exclude: df.exclude,
})
}

func (df *DomainFilter) UnmarshalJSON(b []byte) error {
var deserialized domainFilterSerde
err := json.Unmarshal(b, &deserialized)
if err != nil {
return err
}

if deserialized.RegexInclude == "" && deserialized.RegexExclude == "" {
*df = NewDomainFilterWithExclusions(deserialized.Include, deserialized.Exclude)
return nil
}

if len(deserialized.Include) > 0 || len(deserialized.Exclude) > 0 {
return errors.New("cannot have both domain list and regex")
}

var include, exclude *regexp.Regexp
if deserialized.RegexInclude != "" {
include, err = regexp.Compile(deserialized.RegexInclude)
if err != nil {
return fmt.Errorf("invalid regexInclude: %w", err)
}
}
if deserialized.RegexExclude != "" {
exclude, err = regexp.Compile(deserialized.RegexExclude)
if err != nil {
return fmt.Errorf("invalid regexExclude: %w", err)
}
}
*df = NewRegexDomainFilter(include, exclude)
return nil
}
Loading

0 comments on commit 659c4fb

Please sign in to comment.