Skip to content

Commit aa4144c

Browse files
author
Paul FREAKN Baker
committed
Similar pattern to json unmarshaler but utilizing a generic
1 parent 84e3a7b commit aa4144c

File tree

2 files changed

+23
-16
lines changed

2 files changed

+23
-16
lines changed

regexstruct_118.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@ package regexstruct
66
import (
77
"fmt"
88
"regexp"
9-
10-
"github.com/mitchellh/mapstructure"
119
)
1210

1311
type NoMatchError struct {
@@ -20,13 +18,17 @@ func (nme NoMatchError) Error() string {
2018
return fmt.Sprintf("the regex (%s) did not match the input string (%s)", pattern, nme.input)
2119
}
2220

23-
func RegexMatch[T any](r *regexp.Regexp, s string, item *T) error {
21+
type Unmarshaler interface {
22+
Unmarshal(map[string]string) error
23+
}
24+
25+
func RegexMatch[T Unmarshaler](r *regexp.Regexp, s string, item T) error {
2426
matchedMap, isMatch := RegexMatchMap(r, s)
2527
if !isMatch {
2628
return NoMatchError{
2729
regex: r,
2830
input: s,
2931
}
3032
}
31-
return mapstructure.Decode(matchedMap, item)
33+
return item.Unmarshal(matchedMap)
3234
}

regexstruct_118_test.go

+17-12
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,28 @@ import (
1010
"github.com/stretchr/testify/assert"
1111
)
1212

13+
type example struct {
14+
first string
15+
second string
16+
}
17+
18+
func (e *example) Unmarshal(m map[string]string) error {
19+
e.first = m["first"]
20+
e.second = m["second"]
21+
return nil
22+
}
23+
1324
func TestRegexMatch(t *testing.T) {
1425
regex := regexp.MustCompile(`/(?P<first>\w+)/(?P<second>\w+)`)
1526
input := "/this_is_first/this_is_second"
16-
expected := struct {
17-
First string
18-
Second string
19-
}{
20-
First: "this_is_first",
21-
Second: "this_is_second",
27+
expected := example{
28+
first: "this_is_first",
29+
second: "this_is_second",
2230
}
23-
actual := struct {
24-
First string
25-
Second string
26-
}{}
31+
actual := example{}
2732
err := RegexMatch(regex, input, &actual)
2833
assert.NoError(t, err)
2934

30-
assert.Equal(t, expected.First, actual.First)
31-
assert.Equal(t, expected.Second, actual.Second)
35+
assert.Equal(t, expected.first, actual.first)
36+
assert.Equal(t, expected.second, actual.second)
3237
}

0 commit comments

Comments
 (0)