/
user.go
110 lines (100 loc) · 2.3 KB
/
user.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.JSON("t", &T{}).
Optional(),
field.JSON("url", &url.URL{}).
Optional(),
field.JSON("URLs", []*url.URL{}).
StorageKey("urls").
StructTag(`json:"urls,omitempty"`).
Optional(),
field.JSON("raw", json.RawMessage{}).
Optional(),
field.JSON("dirs", []http.Dir{}).
Default(func() []http.Dir {
return []http.Dir{"/tmp"}
}),
field.Ints("ints").
Optional().
Default([]int{1, 2, 3}),
field.Floats("floats").
Optional(),
field.Strings("strings").
Optional(),
field.JSON("addr", Addr{}).
Sensitive().
Optional(),
field.Any("unknown").
Optional(),
}
}
type T struct {
I int `json:"i,omitempty"`
F float64 `json:"f,omitempty"`
B bool `json:"b,omitempty"`
S string `json:"s,omitempty"`
T *T `json:"t,omitempty"`
Li []int `json:"li"`
Ls []string `json:"ls"`
// Do not omit empty or null maps.
M map[string]any `json:"m"`
}
type Addr struct{ net.Addr }
func (a *Addr) UnmarshalJSON(data []byte) error {
var types struct {
TCP *net.TCPAddr `json:"tcp,omitempty"`
UDP *net.UDPAddr `json:"udp,omitempty"`
}
if err := json.Unmarshal(data, &types); err != nil {
return err
}
switch {
case types.TCP != nil && types.UDP != nil:
return errors.New("TCP and UDP addresses are mutually exclusive")
case types.TCP != nil:
a.Addr = types.TCP
case types.UDP != nil:
a.Addr = types.UDP
}
return nil
}
func (a Addr) MarshalJSON() ([]byte, error) {
var types struct {
TCP *net.TCPAddr `json:"tcp,omitempty"`
UDP *net.UDPAddr `json:"udp,omitempty"`
}
switch a := a.Addr.(type) {
case *net.TCPAddr:
types.TCP = a
case *net.UDPAddr:
types.UDP = a
default:
return nil, fmt.Errorf("unsupported address type: %T", a)
}
return json.Marshal(types)
}
func (a Addr) String() string {
if a.Addr == nil {
return ""
}
return a.Addr.String()
}