File tree 2 files changed +23
-16
lines changed
2 files changed +23
-16
lines changed Original file line number Diff line number Diff line change @@ -6,8 +6,6 @@ package regexstruct
6
6
import (
7
7
"fmt"
8
8
"regexp"
9
-
10
- "github.com/mitchellh/mapstructure"
11
9
)
12
10
13
11
type NoMatchError struct {
@@ -20,13 +18,17 @@ func (nme NoMatchError) Error() string {
20
18
return fmt .Sprintf ("the regex (%s) did not match the input string (%s)" , pattern , nme .input )
21
19
}
22
20
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 {
24
26
matchedMap , isMatch := RegexMatchMap (r , s )
25
27
if ! isMatch {
26
28
return NoMatchError {
27
29
regex : r ,
28
30
input : s ,
29
31
}
30
32
}
31
- return mapstructure . Decode (matchedMap , item )
33
+ return item . Unmarshal (matchedMap )
32
34
}
Original file line number Diff line number Diff line change @@ -10,23 +10,28 @@ import (
10
10
"github.com/stretchr/testify/assert"
11
11
)
12
12
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
+
13
24
func TestRegexMatch (t * testing.T ) {
14
25
regex := regexp .MustCompile (`/(?P<first>\w+)/(?P<second>\w+)` )
15
26
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" ,
22
30
}
23
- actual := struct {
24
- First string
25
- Second string
26
- }{}
31
+ actual := example {}
27
32
err := RegexMatch (regex , input , & actual )
28
33
assert .NoError (t , err )
29
34
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 )
32
37
}
You can’t perform that action at this time.
0 commit comments