refactor the error handling and optimize the heap allocation

This commit is contained in:
2025-05-04 13:32:31 +10:00
parent 4abc00f07c
commit 0c1a9fb7e7
6 changed files with 242 additions and 66 deletions

View File

@@ -18,10 +18,11 @@ package config
import (
"fmt"
"gitea.suyono.dev/suyono/netbounce/abstract"
"maps"
"slices"
"gitea.suyono.dev/suyono/netbounce/abstract"
"github.com/spf13/viper"
)
@@ -83,6 +84,10 @@ func GetConnection(name string) (abstract.ConnectionConfig, error) {
tcp.Name = name
tcp.Type = abstract.TCP
module := tcpModule{config: tcp}
if err = module.Validate(); err != nil {
return nil, fmt.Errorf("tcp config: %w", err)
}
return tcpModule{config: tcp}, nil
default:
return nil, fmt.Errorf("connection %s: invalid connection type: %s", name, configType)

View File

@@ -23,11 +23,13 @@ import (
)
type tcpConfig struct {
Name string `mapstructure:"-,"`
Type abstract.ConnectionType `mapstructure:"-,"`
Listen string `mapstructure:"listen"`
Backend string `mapstructure:"backend"`
KeepAlive bool `mapstructure:"keepalive,false"`
Name string `mapstructure:"-,"`
Type abstract.ConnectionType `mapstructure:"-,"`
Listen string `mapstructure:"listen"`
Backend string `mapstructure:"backend"`
KeepAlive bool `mapstructure:"keepalive,false"`
ReadRetry int `mapstructure:"read-retry,5"`
WriteRetry int `mapstructure:"write-retry,5"`
}
type tcpModule struct {
@@ -62,3 +64,19 @@ func (t tcpModule) AsUDP() abstract.UDPConnectionConfig {
panic(fmt.Errorf("not UDP"))
// return nil
}
func (t tcpModule) ReadRetry() int {
return t.config.ReadRetry
}
func (t tcpModule) WriteRetry() int {
return t.config.WriteRetry
}
func (t tcpModule) Validate() error {
if t.ReadRetry() <= 0 || t.WriteRetry() <= 0 {
return fmt.Errorf("invalid retry config value")
}
return nil
}