forked from naggie/dsnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exttypes.go
85 lines (65 loc) · 1.43 KB
/
exttypes.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
package dsnet
import (
"net"
"strings"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
type JSONIPNet struct {
IPNet net.IPNet
}
func (n JSONIPNet) MarshalJSON() ([]byte, error) {
if len(n.IPNet.IP) == 0 {
return []byte("\"\""), nil
} else {
return []byte("\"" + n.IPNet.String() + "\""), nil
}
}
func (n *JSONIPNet) UnmarshalJSON(b []byte) error {
cidr := strings.Trim(string(b), "\"")
if cidr == "" {
// Leave as empty/uninitialised IPNet. A bit like omitempty behaviour,
// but we can leave the field there and blank which is useful if the
// user wishes to add the cidr manually.
return nil
}
IP, IPNet, err := net.ParseCIDR(cidr)
if err == nil {
IPNet.IP = IP
n.IPNet = *IPNet
}
return err
}
func (n *JSONIPNet) String() string {
return n.IPNet.String()
}
type JSONKey struct {
Key wgtypes.Key
}
func (k JSONKey) MarshalJSON() ([]byte, error) {
return []byte("\"" + k.Key.String() + "\""), nil
}
func (k JSONKey) PublicKey() JSONKey {
return JSONKey{
Key: k.Key.PublicKey(),
}
}
func (k *JSONKey) UnmarshalJSON(b []byte) error {
b64Key := strings.Trim(string(b), "\"")
key, err := wgtypes.ParseKey(b64Key)
k.Key = key
return err
}
func GenerateJSONPrivateKey() JSONKey {
privateKey, err := wgtypes.GeneratePrivateKey()
check(err)
return JSONKey{
Key: privateKey,
}
}
func GenerateJSONKey() JSONKey {
privateKey, err := wgtypes.GenerateKey()
check(err)
return JSONKey{
Key: privateKey,
}
}