gohttp/model/names.go

54 lines
947 B
Go

package model
import (
"encoding/json"
"errors"
"strings"
)
type Strings struct {
Values interface{}
}
func (s *Strings) UnmarshalJSON(data []byte) error {
var raw interface{}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
switch v := raw.(type) {
case string:
s.Values = v
return nil
case []interface{}:
for _, item := range v {
if _, ok := item.(string); !ok {
return errors.New("invalid type in array, expected string")
}
}
s.Values = v
return nil
default:
return errors.New("invalid type")
}
}
func (s *Strings) MarshalJSON() ([]byte, error) {
return json.Marshal(s.Values)
}
func (s *Strings) HasOrContainPrefix(value string) bool {
switch v := s.Values.(type) {
case []interface{}:
for _, item := range v {
if strings.HasPrefix(value, item.(string)) {
return true
}
}
return false
case string:
return strings.HasPrefix(value, v)
default:
return false
}
}