-
Notifications
You must be signed in to change notification settings - Fork 46
/
audience.go
46 lines (41 loc) · 948 Bytes
/
audience.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
package jwt
import "encoding/json"
// Audience is a special claim that be a single string or an array of strings
// See: https://tools.ietf.org/html/rfc7519
type Audience []string
// MarshalJSON implements a marshaling function for "aud" claim.
func (a Audience) MarshalJSON() ([]byte, error) {
switch len(a) {
case 0:
return []byte(`""`), nil
case 1:
return json.Marshal(a[0])
default:
return json.Marshal([]string(a))
}
}
// UnmarshalJSON implements json.Unmarshaler interface.
func (a *Audience) UnmarshalJSON(b []byte) error {
var v any
if err := json.Unmarshal(b, &v); err != nil {
return ErrAudienceInvalidFormat
}
switch v := v.(type) {
case string:
*a = Audience{v}
return nil
case []any:
aud := make(Audience, len(v))
for i := range v {
v, ok := v[i].(string)
if !ok {
return ErrAudienceInvalidFormat
}
aud[i] = v
}
*a = aud
return nil
default:
return ErrAudienceInvalidFormat
}
}