-
Notifications
You must be signed in to change notification settings - Fork 1
/
idn.go
136 lines (113 loc) · 2.43 KB
/
idn.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Froxy - HTTP over SSH proxy
//
// Copyright (C) 2019 and up by Alexander Pevzner (pzz@apevzner.com)
// See LICENSE for license terms and conditions
//
// IDN support
package main
import (
"bytes"
"encoding/json"
"strings"
"golang.org/x/net/idna"
)
//
// IDN version of ServerParams
//
type IDNServerParams ServerParams
var _ = json.Marshaler(&IDNServerParams{})
var _ = json.Unmarshaler(&IDNServerParams{})
//
// Marshal IDNServerParams to JSON. Recodes host name to IDN on a fly
//
func (p *IDNServerParams) MarshalJSON() ([]byte, error) {
out := ServerParams(*p)
out.Addr = IDNDecode(out.Addr)
return json.Marshal(out)
}
//
// Unarshal IDNServerParams from JSON. Recodes host name to IDN on a fly
//
func (p *IDNServerParams) UnmarshalJSON(data []byte) error {
in := ServerParams{}
err := json.Unmarshal(data, &in)
if err != nil {
return err
}
in.Addr = IDNEncode(in.Addr)
*p = IDNServerParams(in)
return nil
}
//
// IDN version of SiteParams
//
type IDNSiteParams SiteParams
var _ = json.Marshaler(&IDNSiteParams{})
var _ = json.Unmarshaler(&IDNSiteParams{})
//
// Marshal IDNSiteParams to JSON. Recodes host name to IDN on a fly
//
func (p *IDNSiteParams) MarshalJSON() ([]byte, error) {
out := SiteParams(*p)
out.Host = IDNDecode(out.Host)
return json.Marshal(out)
}
//
// Unarshal IDNSiteParams from JSON. Recodes host name to IDN on a fly
//
func (p *IDNSiteParams) UnmarshalJSON(data []byte) error {
in := SiteParams{}
err := json.Unmarshal(data, &in)
if err != nil {
return err
}
in.Host = IDNEncode(in.Host)
*p = IDNSiteParams(in)
return nil
}
//
// IDN version of []SiteParams
//
type IDNSiteParamsList []SiteParams
var _ = json.Marshaler(IDNSiteParamsList(nil))
//
// Marshal IDNSiteParams to JSON. Recodes host name to IDN on a fly
//
func (list IDNSiteParamsList) MarshalJSON() ([]byte, error) {
buf := bytes.Buffer{}
buf.WriteByte('[')
for i := range list {
data, err := (*IDNSiteParams)(&list[i]).MarshalJSON()
if err != nil {
return nil, err
}
if i != 0 {
buf.WriteByte(',')
}
buf.Write(data)
}
buf.WriteByte(']')
return buf.Bytes(), nil
}
//
// Decode string from IDN to UNICODE
//
func IDNDecode(in string) string {
out, err := idna.ToUnicode(in)
if err == nil {
return out
} else {
return in
}
}
//
// Encode string from UNICODE to IDN
//
func IDNEncode(in string) string {
out, err := idna.ToASCII(strings.ToLower(in))
if err == nil {
return out
} else {
return in
}
}