/
name.go
41 lines (33 loc) · 905 Bytes
/
name.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package model
import (
"errors"
"fmt"
"regexp"
)
var (
nameRegexp = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`)
ErrIllegalName = errors.New("illegal name")
)
type Name string
func (instance *Name) Set(plain string) error {
return instance.UnmarshalText([]byte(plain))
}
func (instance Name) String() string {
v, _ := instance.MarshalText()
return string(v)
}
func (instance Name) MarshalText() (text []byte, err error) {
if len(instance) > 0 && (!nameRegexp.MatchString(string(instance)) || len(instance) > 253) {
return []byte(fmt.Sprintf("illegal-name-%s", string(instance))),
fmt.Errorf("%w: %s", ErrIllegalName, string(instance))
}
return []byte(instance), nil
}
func (instance *Name) UnmarshalText(text []byte) error {
v := Name(text)
if _, err := instance.MarshalText(); err != nil {
return err
}
*instance = v
return nil
}