File: user.go

package info (click to toggle)
golang-entgo-ent 0.11.3-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 21,976 kB
  • sloc: javascript: 641; makefile: 8; sql: 2
file content (104 lines) | stat: -rw-r--r-- 2,228 bytes parent folder | download | duplicates (2)
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
// 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("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(),
	}
}

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,omitempty"`
	Ls []string `json:"ls,omitempty"`
	// 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()
}