-
Notifications
You must be signed in to change notification settings - Fork 0
/
role.go
67 lines (54 loc) · 1.35 KB
/
role.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package user
import "fmt"
// Set of possible roles for a user.
var (
RoleAdmin = Role{"ADMIN"}
RoleUser = Role{"USER"}
)
// Set of known roles.
var roles = map[string]Role{
RoleAdmin.name: RoleAdmin,
RoleUser.name: RoleUser,
}
// Role represents a role in the system.
type Role struct {
name string
}
// ParseRole parses the string value and returns a role if one exists.
func ParseRole(value string) (Role, error) {
role, exists := roles[value]
if !exists {
return Role{}, fmt.Errorf("invalid role %q", value)
}
return role, nil
}
// MustParseRole parses the string value and returns a role if one exists. If
// an error occurs the function panics.
func MustParseRole(value string) Role {
role, err := ParseRole(value)
if err != nil {
panic(err)
}
return role
}
// Name returns the name of the role.
func (r Role) Name() string {
return r.name
}
// UnmarshalText implement the unmarshal interface for JSON conversions.
func (r *Role) UnmarshalText(data []byte) error {
role, err := ParseRole(string(data))
if err != nil {
return err
}
r.name = role.name
return nil
}
// MarshalText implement the marshal interface for JSON conversions.
func (r Role) MarshalText() ([]byte, error) {
return []byte(r.name), nil
}
// Equal provides support for the go-cmp package and testing.
func (r Role) Equal(r2 Role) bool {
return r.name == r2.name
}