netbounce/config/config.go

91 lines
2.2 KiB
Go

package config
/*
Copyright 2025 Suyono <suyono3484@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import (
"fmt"
"gitea.suyono.dev/suyono/netbounce/abstract"
"maps"
"slices"
"github.com/spf13/viper"
)
const (
CONNECTION = "connection"
TYPE = "type"
UDP = "udp"
TCP = "tcp"
)
func ReadConfig() error {
viper.SetDefault("config", "/etc/netbounce/netbounce.yml")
configPath := viper.GetString("config")
viper.SetConfigFile(configPath)
viper.SetConfigType("yaml")
if err := viper.ReadInConfig(); err != nil {
return fmt.Errorf("reading config file %s: %w", configPath, err)
}
return nil
}
func ListConnection() ([]string, error) {
m := viper.GetStringMap(CONNECTION)
l := slices.Collect(maps.Keys(m))
if len(l) == 0 {
return nil, fmt.Errorf("no connection found")
}
return l, nil
}
func GetConnection(name string) (abstract.ConnectionConfig, error) {
var (
tcp tcpConfig
udp udpConfig
err error
)
configType := viper.GetString(fmt.Sprintf("%s.%s.%s", CONNECTION, name, TYPE))
if configType == "" {
return nil, fmt.Errorf("no connection found")
}
configKey := fmt.Sprintf("%s.%s", CONNECTION, name)
switch configType {
case UDP:
if err = viper.UnmarshalKey(configKey, &udp); err != nil {
return nil, fmt.Errorf("unmarshal config %s: %w", configKey, err)
}
udp.Name = name
udp.Type = abstract.UDP
return udpModule{config: udp}, nil
case TCP:
if err = viper.UnmarshalKey(configKey, &tcp); err != nil {
return nil, fmt.Errorf("unmarshal config %s: %w", configKey, err)
}
tcp.Name = name
tcp.Type = abstract.TCP
return tcpModule{config: tcp}, nil
default:
return nil, fmt.Errorf("connection %s: invalid connection type: %s", name, configType)
}
}