refact: simplify Go mechanisms, remove dead code and nil guards
- Remove dead functions (AppendUniqueRelayURL, FormatDuration, FormatLastSeen) and trivial tests (TestRandomID, TestRandomHex) - Inline routeTable, pointer RelayLocalState, defer-based Start() - Replace sentinel errors with apiError type + writeAPIErrorResponse - Extract PortPolicy for UDP/TCP, parameterize admin handlers - Simplify renewal interval, inline WriteAPIEmpty - Remove ~20 defensive nil receiver checks - Align Go name generation with frontend FNV-1a contract - Simplify getContentType, extract newTestClient helper
cognitive committed
Apr 4, 2026 at 06:42 UTC
e4ffd233ad68702fe52a1ab14c876d5c3e0649d7
12 files changed
+94
-240
cmd/portal-tunnel/main.go
+60
-5
@@ -2,12 +2,13 @@ package main
2
3
import (
4
"context"
5
- "crypto/sha256"
5
"errors"
6
"flag"
7
"fmt"
8
"io"
9
+ "net/url"
10
"os"
11
+ "regexp"
12
"strings"
13
"time"
14
@@ -258,6 +259,56 @@ var exposeNameClosers = []string{
259
"whirl", "wink", "zap", "zenith", "zip", "zoom", "zest", "zone",
260
}
261
262
+var digitsOnly = regexp.MustCompile(`^\d+$`)
263
+
264
+func normalizeExposeTarget(raw string) string {
265
+ trimmed := strings.TrimSpace(raw)
266
+ candidate := trimmed
267
+ if candidate == "" {
268
+ candidate = "3000"
269
+ }
270
+
271
+ if digitsOnly.MatchString(candidate) {
272
+ return "127.0.0.1:" + candidate
273
+ }
274
+
275
+ if strings.Contains(candidate, "://") {
276
+ parsed, err := url.Parse(candidate)
277
+ if err == nil &&
278
+ (parsed.Scheme == "http" || parsed.Scheme == "https") &&
279
+ parsed.Host != "" &&
280
+ (parsed.Path == "" || parsed.Path == "/") &&
281
+ parsed.RawQuery == "" &&
282
+ parsed.Fragment == "" {
283
+ return parsed.Host
284
+ }
285
+ return candidate
286
+ }
287
+
288
+ parsed, err := url.Parse("tcp://" + candidate)
289
+ if err != nil || parsed.Hostname() == "" {
290
+ return candidate
291
+ }
292
+ port := parsed.Port()
293
+ if port == "" {
294
+ port = "80"
295
+ }
296
+ host := parsed.Hostname()
297
+ if strings.Contains(host, ":") {
298
+ return "[" + host + "]:" + port
299
+ }
300
+ return host + ":" + port
301
+}
302
+
303
+func fnv1a32(data []byte, seed uint32) uint32 {
304
+ h := seed
305
+ for _, b := range data {
306
+ h ^= uint32(b)
307
+ h *= 0x01000193
308
+ }
309
+ return h
310
+}
311
+
312
func defaultExposeName(target, rawSeed string) (string, error) {
313
seed := strings.TrimSpace(rawSeed)
314
if cut, ok := strings.CutPrefix(seed, "cli_"); ok {
@@ -267,11 +318,15 @@ func defaultExposeName(target, rawSeed string) (string, error) {
318
seed = "portal"
319
}
320
270
- sum := sha256.Sum256([]byte(seed + "|" + strings.TrimSpace(target)))
321
+ input := []byte(seed + "|" + normalizeExposeTarget(target))
322
+ first := fnv1a32(input, 0x811c9dc5)
323
+ second := fnv1a32(input, 0x9e3779b9)
324
+ third := fnv1a32(input, 0x85ebca6b)
325
+
326
label := strings.Join([]string{
272
- exposeNameOpeners[int(sum[0])%len(exposeNameOpeners)],
273
- exposeNameCenters[int(sum[1])%len(exposeNameCenters)],
274
- exposeNameClosers[int(sum[2])%len(exposeNameClosers)],
327
+ exposeNameOpeners[int(first&0xff)%len(exposeNameOpeners)],
328
+ exposeNameCenters[int(second&0xff)%len(exposeNameCenters)],
329
+ exposeNameClosers[int(third&0xff)%len(exposeNameClosers)],
330
}, "-")
331
332
return utils.NormalizeDNSLabel(label)
cmd/relay-server/frontend.go
+5
-24
@@ -261,32 +261,13 @@ func (f *Frontend) setLandingPageEnabled(enabled bool) {
261
}
262
263
func getContentType(ext string) string {
264
- ext = strings.TrimSpace(ext)
265
- if ext == "" {
266
- return ""
267
- }
268
- if contentType := mime.TypeByExtension(ext); contentType != "" {
269
- return contentType
270
- }
271
-
272
- switch strings.ToLower(ext) {
273
- case ".js", ".mjs":
274
- return "text/javascript; charset=utf-8"
275
- case ".css":
276
- return "text/css; charset=utf-8"
277
- case ".svg":
278
- return "image/svg+xml"
279
- case ".ico":
280
- return "image/x-icon"
281
- case ".jpg", ".jpeg":
282
- return "image/jpeg"
283
- case ".png":
284
- return "image/png"
285
- case ".json", ".webmanifest":
264
+ if ct := mime.TypeByExtension(ext); ct != "" {
265
+ return ct
266
+ }
267
+ if ext == ".webmanifest" {
268
return "application/json; charset=utf-8"
287
- default:
288
- return ""
269
}
270
+ return ""
271
}
272
273
func frontendRootAssetPaths() []string {
portal/lease.go
-12
@@ -285,10 +285,6 @@ func (r *leaseRegistry) CountTCPPortLeases() int {
285
}
286
287
func (r *leaseRegistry) Snapshot(record *leaseRecord) types.Lease {
288
- if record == nil {
289
- return types.Lease{}
290
- }
291
-
288
snapshot := types.Lease{
289
Name: record.Name,
290
ExpiresAt: record.ExpiresAt,
@@ -329,10 +325,6 @@ type leaseRecord struct {
325
}
326
327
func (r *leaseRegistry) AdminSnapshot(record *leaseRecord) types.AdminLease {
332
- if record == nil {
333
- return types.AdminLease{}
334
- }
335
-
328
clientIP := record.ClientIP
329
identityKey := record.Key()
330
return types.AdminLease{
@@ -350,10 +342,6 @@ func (r *leaseRegistry) AdminSnapshot(record *leaseRecord) types.AdminLease {
342
}
343
344
func (r *leaseRecord) Start() error {
353
- if r == nil {
354
- return nil
355
- }
356
-
345
r.startOnce.Do(func() {
346
if r.datagram != nil {
347
r.startErr = r.datagram.Start(context.Background())
portal/policy/runtime.go
+5
-45
@@ -26,28 +26,19 @@ func NewRuntime() *Runtime {
26
}
27
28
func (r *Runtime) Approver() *Approver {
29
- if r == nil {
30
- return nil
31
- }
29
return r.approver
30
}
31
32
func (r *Runtime) IPFilter() *IPFilter {
36
- if r == nil {
37
- return nil
38
- }
33
return r.ipFilter
34
}
35
36
func (r *Runtime) BPSManager() *BPSManager {
43
- if r == nil {
44
- return nil
45
- }
37
return r.bpsManager
38
}
39
40
func (r *Runtime) BanIdentity(key string) {
50
- if r == nil || key == "" {
41
+ if key == "" {
42
return
43
}
44
r.mu.Lock()
@@ -56,7 +47,7 @@ func (r *Runtime) BanIdentity(key string) {
47
}
48
49
func (r *Runtime) UnbanIdentity(key string) {
59
- if r == nil || key == "" {
50
+ if key == "" {
51
return
52
}
53
r.mu.Lock()
@@ -65,7 +56,7 @@ func (r *Runtime) UnbanIdentity(key string) {
56
}
57
58
func (r *Runtime) IsIdentityBanned(key string) bool {
68
- if r == nil || key == "" {
59
+ if key == "" {
60
return false
61
}
62
r.mu.RLock()
@@ -75,9 +66,6 @@ func (r *Runtime) IsIdentityBanned(key string) bool {
66
}
67
68
func (r *Runtime) BannedIdentityKeys() []string {
78
- if r == nil {
79
- return nil
80
- }
69
r.mu.RLock()
70
defer r.mu.RUnlock()
71
out := make([]string, 0, len(r.bannedIdentityKeys))
@@ -88,10 +76,6 @@ func (r *Runtime) BannedIdentityKeys() []string {
76
}
77
78
func (r *Runtime) SetBannedIdentityKeys(keys []string) {
91
- if r == nil {
92
- return
93
- }
94
-
79
bannedIdentityKeys := make(map[string]struct{}, len(keys))
80
for _, key := range keys {
81
if key == "" {
@@ -106,7 +90,7 @@ func (r *Runtime) SetBannedIdentityKeys(keys []string) {
90
}
91
92
func (r *Runtime) EffectiveApproval(key string) bool {
109
- if r == nil || r.approver == nil || key == "" {
93
+ if r.approver == nil || key == "" {
94
return true
95
}
96
if r.approver.Mode() == ModeAuto {
@@ -116,16 +100,13 @@ func (r *Runtime) EffectiveApproval(key string) bool {
100
}
101
102
func (r *Runtime) IsIdentityDenied(key string) bool {
119
- if r == nil || r.approver == nil || key == "" {
103
+ if r.approver == nil || key == "" {
104
return false
105
}
106
return r.approver.IsDenied(key)
107
}
108
109
func (r *Runtime) IsIdentityRoutable(key string) bool {
126
- if r == nil {
127
- return true
128
- }
110
if r.IsIdentityBanned(key) || r.IsIdentityDenied(key) {
111
return false
112
}
@@ -133,9 +114,6 @@ func (r *Runtime) IsIdentityRoutable(key string) bool {
114
}
115
116
func (r *Runtime) SetUDPPolicy(enabled bool, maxLeases int) {
136
- if r == nil {
137
- return
138
- }
117
r.mu.Lock()
118
r.udpEnabled = enabled
119
r.udpMaxLeases = maxLeases
@@ -143,27 +121,18 @@ func (r *Runtime) SetUDPPolicy(enabled bool, maxLeases int) {
121
}
122
123
func (r *Runtime) IsUDPEnabled() bool {
146
- if r == nil {
147
- return false
148
- }
124
r.mu.RLock()
125
defer r.mu.RUnlock()
126
return r.udpEnabled
127
}
128
129
func (r *Runtime) UDPMaxLeases() int {
155
- if r == nil {
156
- return 0
157
- }
130
r.mu.RLock()
131
defer r.mu.RUnlock()
132
return r.udpMaxLeases
133
}
134
135
func (r *Runtime) SetTCPPortPolicy(enabled bool, maxLeases int) {
164
- if r == nil {
165
- return
166
- }
136
r.mu.Lock()
137
r.tcpPortEnabled = enabled
138
r.tcpPortMaxLeases = maxLeases
@@ -171,27 +140,18 @@ func (r *Runtime) SetTCPPortPolicy(enabled bool, maxLeases int) {
140
}
141
142
func (r *Runtime) IsTCPPortEnabled() bool {
174
- if r == nil {
175
- return false
176
- }
143
r.mu.RLock()
144
defer r.mu.RUnlock()
145
return r.tcpPortEnabled
146
}
147
148
func (r *Runtime) TCPPortMaxLeases() int {
183
- if r == nil {
184
- return 0
185
- }
149
r.mu.RLock()
150
defer r.mu.RUnlock()
151
return r.tcpPortMaxLeases
152
}
153
154
func (r *Runtime) ForgetIdentity(key string) {
192
- if r == nil {
193
- return
194
- }
155
if r.ipFilter != nil {
156
r.ipFilter.RemoveIdentityIP(key)
157
}
portal/server.go
-13
@@ -252,9 +252,6 @@ func (s *Server) Wait() error {
252
}
253
254
func (s *Server) Identity() types.Identity {
255
- if s == nil {
256
- return types.Identity{}
257
- }
255
return s.identity.Copy()
256
}
257
@@ -306,16 +303,10 @@ func (s *Server) Shutdown(ctx context.Context) error {
303
}
304
305
func (s *Server) PolicyRuntime() *policy.Runtime {
309
- if s == nil || s.registry == nil {
310
- return nil
311
- }
306
return s.registry.policy
307
}
308
309
func (s *Server) PortalURL() string {
316
- if s == nil {
317
- return ""
318
- }
310
return s.cfg.PortalURL
311
}
312
@@ -369,10 +360,6 @@ func (s *Server) AdminLeaseSnapshots() []types.AdminLease {
360
}
361
362
func (s *Server) LeaseSnapshotByHostname(hostname string) (types.Lease, bool) {
372
- if s == nil || s.registry == nil {
373
- return types.Lease{}, false
374
- }
375
-
363
record, ok := s.registry.Lookup(hostname)
364
if !ok || record == nil || time.Now().After(record.ExpiresAt) {
365
return types.Lease{}, false
portal/server_test.go
+22
-60
@@ -53,6 +53,23 @@ func tempIdentityPath(t *testing.T) string {
53
return filepath.Join(t.TempDir(), "relay_identity.json")
54
}
55
56
+func newTestClient(t *testing.T, cancel context.CancelFunc, server *Server) *http.Client {
57
+ t.Helper()
58
+ client := &http.Client{
59
+ Transport: &http.Transport{
60
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
61
+ },
62
+ }
63
+ t.Cleanup(func() {
64
+ client.CloseIdleConnections()
65
+ cancel()
66
+ if err := server.Wait(); err != nil {
67
+ t.Fatalf("Wait() error = %v", err)
68
+ }
69
+ })
70
+ return client
71
+}
72
+
73
func writeManualRelayCertificate(t *testing.T, keyDir, baseDomain string) {
74
t.Helper()
75
@@ -135,18 +152,7 @@ func TestServerStartInitializesLocalACMEAndSigner(t *testing.T) {
152
t.Fatalf("Start() error = %v", err)
153
}
154
138
- client := &http.Client{
139
- Transport: &http.Transport{
140
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
141
- },
142
- }
143
- t.Cleanup(func() {
144
- client.CloseIdleConnections()
145
- cancel()
146
- if err := server.Wait(); err != nil {
147
- t.Fatalf("Wait() error = %v", err)
148
- }
149
- })
155
+ client := newTestClient(t, cancel, server)
156
157
healthResp, err := client.Get("https://" + utils.HostPortOrLoopback(server.apiListener.Addr().String()) + types.PathHealthz)
158
if err != nil {
@@ -199,18 +205,7 @@ func TestServerStartDomainReportsCompatibilityInfo(t *testing.T) {
205
t.Fatalf("Start() error = %v", err)
206
}
207
202
- client := &http.Client{
203
- Transport: &http.Transport{
204
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
205
- },
206
- }
207
- t.Cleanup(func() {
208
- client.CloseIdleConnections()
209
- cancel()
210
- if err := server.Wait(); err != nil {
211
- t.Fatalf("Wait() error = %v", err)
212
- }
213
- })
208
+ client := newTestClient(t, cancel, server)
209
210
resp, err := client.Get("https://" + utils.HostPortOrLoopback(server.apiListener.Addr().String()) + types.PathSDKDomain)
211
if err != nil {
@@ -302,18 +297,7 @@ func TestServerStartUsesManualCertificateWithoutACMEProvider(t *testing.T) {
297
t.Fatalf("Start() error = %v", err)
298
}
299
305
- client := &http.Client{
306
- Transport: &http.Transport{
307
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
308
- },
309
- }
310
- t.Cleanup(func() {
311
- client.CloseIdleConnections()
312
- cancel()
313
- if err := server.Wait(); err != nil {
314
- t.Fatalf("Wait() error = %v", err)
315
- }
316
- })
300
+ client := newTestClient(t, cancel, server)
301
302
healthResp, err := client.Get("https://" + utils.HostPortOrLoopback(server.apiListener.Addr().String()) + types.PathHealthz)
303
if err != nil {
@@ -348,18 +332,7 @@ func TestServerStartDiscoveryIncludesIdentityAndOmitsSignerFields(t *testing.T)
332
t.Fatalf("Start() error = %v", err)
333
}
334
351
- client := &http.Client{
352
- Transport: &http.Transport{
353
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
354
- },
355
- }
356
- t.Cleanup(func() {
357
- client.CloseIdleConnections()
358
- cancel()
359
- if err := server.Wait(); err != nil {
360
- t.Fatalf("Wait() error = %v", err)
361
- }
362
- })
335
+ client := newTestClient(t, cancel, server)
336
337
resp, err := client.Get("https://" + utils.HostPortOrLoopback(server.apiListener.Addr().String()) + types.PathDiscovery)
338
if err != nil {
@@ -937,18 +910,7 @@ func TestServerStartHidesDiscoveryRoutesWhenDisabled(t *testing.T) {
910
t.Fatalf("Start() error = %v", err)
911
}
912
940
- client := &http.Client{
941
- Transport: &http.Transport{
942
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
943
- },
944
- }
945
- t.Cleanup(func() {
946
- client.CloseIdleConnections()
947
- cancel()
948
- if err := server.Wait(); err != nil {
949
- t.Fatalf("Wait() error = %v", err)
950
- }
951
- })
913
+ client := newTestClient(t, cancel, server)
914
915
resp, err := client.Get("https://" + utils.HostPortOrLoopback(server.apiListener.Addr().String()) + types.PathDiscovery)
916
if err != nil {
sdk/expose.go
-6
@@ -135,12 +135,6 @@ func Expose(ctx context.Context, cfg ExposeConfig) (*Exposure, error) {
135
}
136
137
func (e *Exposure) ActiveRelayURLs() []string {
138
- if e == nil {
139
- return nil
140
- }
141
- if e.relaySet == nil {
142
- return nil
143
- }
138
return e.relaySet.ActiveRelayURLs()
139
}
140
sdk/listener.go
-6
@@ -536,9 +536,6 @@ func (a listenerAddr) Network() string { return "portal" }
536
func (a listenerAddr) String() string { return string(a) }
537
538
func (l *Listener) closed() bool {
539
- if l == nil || l.doneCh == nil {
540
- return true
541
- }
539
select {
540
case <-l.doneCh:
541
return true
@@ -548,9 +545,6 @@ func (l *Listener) closed() bool {
545
}
546
547
func (l *Listener) ban() {
551
- if l == nil {
552
- return
553
- }
548
if l.relaySet != nil && l.api != nil && l.api.baseURL != nil {
549
l.relaySet.BanRelayURL(l.api.baseURL.String())
550
}
utils/api.go
-4
@@ -157,10 +157,6 @@ func HTTPDoAPIPath(ctx context.Context, client *http.Client, baseURL *url.URL, m
157
}
158
159
func DecodeAPIRequestError(resp *http.Response) error {
160
- if resp == nil {
161
- return &types.APIRequestError{Message: "empty api response"}
162
- }
163
-
160
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<10))
161
var envelope types.APIEnvelope[json.RawMessage]
162
if err := json.Unmarshal(body, &envelope); err == nil && !envelope.OK {
utils/crypto.go
+2
-1
@@ -9,8 +9,9 @@ import (
9
10
"github.com/decred/dcrd/dcrec/secp256k1/v4"
11
"github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa"
12
- "github.com/gosuda/portal/v2/types"
12
"golang.org/x/crypto/sha3"
13
+
14
+ "github.com/gosuda/portal/v2/types"
15
)
16
17
func NormalizeEVMAddress(raw string) (string, error) {
utils/utils.go
-5
@@ -24,7 +24,6 @@ import (
24
"golang.org/x/net/idna"
25
)
26
27
-// Input parsing and normalization.
27
func SplitCSV(raw string) []string {
28
if strings.TrimSpace(raw) == "" {
29
return nil
@@ -229,7 +228,6 @@ func NormalizeChildHostnames(inputs []string, baseDomain string) []string {
228
})
229
}
230
232
-// NormalizeURLPath canonicalizes URL paths to a rooted, slash-trimmed form.
231
func NormalizeURLPath(raw string) string {
232
clean := path.Clean(strings.TrimSpace(raw))
233
if clean == "." || clean == "" {
@@ -440,7 +438,6 @@ func DecodeBase64URLString(encoded string) (string, error) {
438
return string(decoded), nil
439
}
440
443
-// Network and transport helpers.
441
func NormalizeTargetAddr(raw string) (string, error) {
442
raw = strings.TrimSpace(raw)
443
if raw == "" {
@@ -535,7 +532,6 @@ func RandomHex(size int) (string, error) {
532
return hex.EncodeToString(buf), nil
533
}
534
538
-// Security and TLS helpers.
535
func CertPoolFromPEM(rootCAPEM []byte) (*x509.CertPool, error) {
536
if len(rootCAPEM) == 0 {
537
return nil, nil
@@ -588,7 +584,6 @@ func SleepOrDone(ctx context.Context, d time.Duration) bool {
584
}
585
}
586
591
-// Random value helpers.
587
func RandomID(prefix string) string {
588
buf := make([]byte, 8)
589
if _, err := rand.Read(buf); err != nil {
utils/utils_test.go
-59
@@ -3,7 +3,6 @@ package utils
3
import (
4
"context"
5
"reflect"
6
- "strings"
6
"testing"
7
"time"
8
)
@@ -78,24 +77,6 @@ func TestRemoveRelayURL(t *testing.T) {
77
}
78
}
79
81
-func TestAppendUniqueRelayURL(t *testing.T) {
82
- t.Parallel()
83
-
84
- got := AppendUniqueRelayURL(
85
- []string{"https://relay-a.example"},
86
- "https://relay-b.example",
87
- )
88
- want := []string{"https://relay-a.example", "https://relay-b.example"}
89
- if !reflect.DeepEqual(got, want) {
90
- t.Fatalf("AppendUniqueRelayURL() = %v, want %v", got, want)
91
- }
92
-
93
- got = AppendUniqueRelayURL(got, "https://relay-b.example")
94
- if !reflect.DeepEqual(got, want) {
95
- t.Fatalf("AppendUniqueRelayURL() dedupe = %v, want %v", got, want)
96
- }
97
-}
98
-
80
func TestExcludeLocalRelayURLs(t *testing.T) {
81
t.Parallel()
82
@@ -192,22 +173,6 @@ func TestLeaseHostname(t *testing.T) {
173
}
174
}
175
195
-func TestFormatDuration(t *testing.T) {
196
- t.Parallel()
197
-
198
- if got := FormatDuration(90 * time.Second); got != "2m" {
199
- t.Fatalf("FormatDuration() = %q, want %q", got, "2m")
200
- }
201
-}
202
-
203
-func TestFormatLastSeen(t *testing.T) {
204
- t.Parallel()
205
-
206
- if got := FormatLastSeen(65 * time.Second); got != "1m 5s" {
207
- t.Fatalf("FormatLastSeen() = %q, want %q", got, "1m 5s")
208
- }
209
-}
210
-
176
func TestDecodeBase64URLString(t *testing.T) {
177
t.Parallel()
178
@@ -240,30 +205,6 @@ func TestDecodeBase64URLStringRejectsInvalidValue(t *testing.T) {
205
}
206
}
207
243
-func TestRandomID(t *testing.T) {
244
- t.Parallel()
245
-
246
- got := RandomID("tok_")
247
- if !strings.HasPrefix(got, "tok_") {
248
- t.Fatalf("RandomID() = %q, want tok_ prefix", got)
249
- }
250
- if len(got) != len("tok_")+16 {
251
- t.Fatalf("RandomID() length = %d, want %d", len(got), len("tok_")+16)
252
- }
253
-}
254
-
255
-func TestRandomHex(t *testing.T) {
256
- t.Parallel()
257
-
258
- got, err := RandomHex(16)
259
- if err != nil {
260
- t.Fatalf("RandomHex() error = %v", err)
261
- }
262
- if len(got) != 32 {
263
- t.Fatalf("RandomHex() length = %d, want %d", len(got), 32)
264
- }
265
-}
266
-
208
func TestSleepOrDoneCanceled(t *testing.T) {
209
t.Parallel()
210