github.com/lyft/flytestdlib@v0.3.12-0.20210213045714-8cdd111ecda1/config/regexp.go (about) 1 package config 2 3 import ( 4 "encoding/json" 5 "errors" 6 "regexp" 7 ) 8 9 // A regexp.Regexp wrapper that can marshal and unmarshal into simple regexp string. 10 type Regexp struct { 11 regexp.Regexp 12 } 13 14 func (r Regexp) MarshalJSON() ([]byte, error) { 15 return json.Marshal(r.String()) 16 } 17 18 func (r *Regexp) UnmarshalJSON(b []byte) error { 19 if len(b) == 0 { 20 r.Regexp = regexp.Regexp{} 21 return nil 22 } 23 24 var v interface{} 25 if err := json.Unmarshal(b, &v); err != nil { 26 return err 27 } 28 29 switch value := v.(type) { 30 case string: 31 rc, err := regexp.Compile(value) 32 if err != nil { 33 return err 34 } 35 36 r.Regexp = *rc 37 return nil 38 default: 39 return errors.New("invalid regexp") 40 } 41 }