refactor(frpc): replace ini with toml for config handling and improve proxy management

- Replace ini package with toml for more reliable config parsing
- Refactor proxy management to use structured config instead of string manipulation
- Add proper error handling for config operations
- Clean up unused imports and improve code organization
- Update go.mod dependencies accordingly
This commit is contained in:
2026-03-19 22:40:12 +08:00
parent c7fc0136b0
commit ab2e0567a9
8 changed files with 232 additions and 224 deletions
BIN
View File
Binary file not shown.
+82 -119
View File
@@ -12,7 +12,7 @@ import (
"super-frpc/postLog" "super-frpc/postLog"
"time" "time"
"gopkg.in/ini.v1" "github.com/BurntSushi/toml"
) )
type InstanceInfo struct { type InstanceInfo struct {
@@ -20,7 +20,6 @@ type InstanceInfo struct {
ServerAddr string `json:"serverAddr"` ServerAddr string `json:"serverAddr"`
ServerPort string `json:"serverPort"` ServerPort string `json:"serverPort"`
AuthMethod string `json:"auth_method"` AuthMethod string `json:"auth_method"`
// BootAtStart bool `json:"bootAtStart"`
RunUser string `json:"runUser"` RunUser string `json:"runUser"`
Additional map[string]interface{} `json:"additionalProperties"` Additional map[string]interface{} `json:"additionalProperties"`
} }
@@ -40,6 +39,12 @@ type CreateInstanceRequest struct {
Additional map[string]interface{} `json:"additionalProperties"` Additional map[string]interface{} `json:"additionalProperties"`
} }
type FrpcConfig struct {
Common map[string]interface{} `toml:"common"`
Proxies []map[string]interface{} `toml:"proxies"`
Additional map[string]interface{} `toml:"-"`
}
var frpcDB *sql.DB var frpcDB *sql.DB
func CloseFrpcDatabase() error { func CloseFrpcDatabase() error {
@@ -64,7 +69,6 @@ func CreateInstanceHandler(w http.ResponseWriter, r *http.Request) {
} }
defer r.Body.Close() defer r.Body.Close()
// 先解析为map,处理类型不匹配的情况
var reqMap map[string]interface{} var reqMap map[string]interface{}
if err := json.Unmarshal(body, &reqMap); err != nil { if err := json.Unmarshal(body, &reqMap); err != nil {
postLog.Error(fmt.Sprintf("[CreateInstanceHandler] Failed to unmarshal request body: %v", err)) postLog.Error(fmt.Sprintf("[CreateInstanceHandler] Failed to unmarshal request body: %v", err))
@@ -72,7 +76,6 @@ func CreateInstanceHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// 处理bootAtStart字段
bootAtStart := false bootAtStart := false
if bas, ok := reqMap["bootAtStart"]; ok { if bas, ok := reqMap["bootAtStart"]; ok {
switch v := bas.(type) { switch v := bas.(type) {
@@ -85,7 +88,6 @@ func CreateInstanceHandler(w http.ResponseWriter, r *http.Request) {
} }
} }
// 处理instanceInfo字段
instanceInfoMap, ok := reqMap["instanceInfo"].(map[string]interface{}) instanceInfoMap, ok := reqMap["instanceInfo"].(map[string]interface{})
if !ok { if !ok {
SendErrorResponse(w, http.StatusBadRequest, "Invalid instanceInfo format") SendErrorResponse(w, http.StatusBadRequest, "Invalid instanceInfo format")
@@ -100,12 +102,10 @@ func CreateInstanceHandler(w http.ResponseWriter, r *http.Request) {
RunUser: getStringFromMap(reqMap, "runUser"), RunUser: getStringFromMap(reqMap, "runUser"),
} }
// 处理additionalProperties字段
if additional, ok := reqMap["additionalProperties"].(map[string]interface{}); ok { if additional, ok := reqMap["additionalProperties"].(map[string]interface{}); ok {
instanceInfo.Additional = additional instanceInfo.Additional = additional
} }
// 从Header中验证token和timeStamp
userID, _, err := ValidateRequestWithHeader(w, r) userID, _, err := ValidateRequestWithHeader(w, r)
if err != nil { if err != nil {
postLog.Error(fmt.Sprintf("[CreateInstanceHandler] Failed to validate request header: %v", err)) postLog.Error(fmt.Sprintf("[CreateInstanceHandler] Failed to validate request header: %v", err))
@@ -113,7 +113,6 @@ func CreateInstanceHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// 构建请求结构体
req := CreateInstanceRequest{ req := CreateInstanceRequest{
InstanceInfo: instanceInfo, InstanceInfo: instanceInfo,
BootAtStart: bootAtStart, BootAtStart: bootAtStart,
@@ -152,7 +151,6 @@ func CreateInstanceHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// Add frpc instance
configFileName := fmt.Sprintf("superfrpc_%s_%s.toml", user.Username, req.InstanceInfo.Name) configFileName := fmt.Sprintf("superfrpc_%s_%s.toml", user.Username, req.InstanceInfo.Name)
configPath := filepath.Join(configDir, configFileName) configPath := filepath.Join(configDir, configFileName)
@@ -190,7 +188,6 @@ func CreateInstanceHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
} }
// Finish add frpc instance
SendSuccessResponse(w, "Instance created successfully", map[string]interface{}{ SendSuccessResponse(w, "Instance created successfully", map[string]interface{}{
"name": req.InstanceInfo.Name, "name": req.InstanceInfo.Name,
@@ -248,12 +245,6 @@ func DeleteInstanceHandler(w http.ResponseWriter, r *http.Request) {
} }
var instance FrpcInstance var instance FrpcInstance
// err = frpcDB.QueryRow(`
// SELECT id, userID, name, serverAddr, serverPort, auth_method, bootAtStart, runUser, configPath, createdAt
// FROM frpcInstances WHERE userID = ? AND name = ?
// `, userID, instanceName).Scan(
// &instance.ID, &instance.UserID, &instance.Name, &instance.ServerAddr, &instance.ServerPort,
// &instance.AuthMethod, &instance.BootAtStart, &instance.RunUser, &instance.ConfigPath, &instance.CreatedAt)
instance, err = DBQueryFrpcInstance(userID, instanceName) instance, err = DBQueryFrpcInstance(userID, instanceName)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
SendErrorResponse(w, http.StatusNotFound, "Instance not found") SendErrorResponse(w, http.StatusNotFound, "Instance not found")
@@ -334,7 +325,7 @@ func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
if modifyType != "configFile" && modifyType != "systemConfig" { // Detect valid modify type if modifyType != "configFile" && modifyType != "systemConfig" {
SendErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("Unknown modify type %s", modifyType)) SendErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("Unknown modify type %s", modifyType))
return return
} }
@@ -345,7 +336,6 @@ func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// 从Header中验证token和timeStamp
userID, _, err := ValidateRequestWithHeader(w, r) userID, _, err := ValidateRequestWithHeader(w, r)
if err != nil { if err != nil {
postLog.Error(fmt.Sprintf("[ModifyInstanceHandler] Failed to validate request header: %v", err)) postLog.Error(fmt.Sprintf("[ModifyInstanceHandler] Failed to validate request header: %v", err))
@@ -378,7 +368,6 @@ func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// 验证 instanceID 是否匹配
if fmt.Sprintf("%d", instance.ID) != instanceID { if fmt.Sprintf("%d", instance.ID) != instanceID {
SendErrorResponse(w, http.StatusBadRequest, "instanceID does not match instanceName") SendErrorResponse(w, http.StatusBadRequest, "instanceID does not match instanceName")
return return
@@ -394,7 +383,6 @@ func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request) {
func handleConfigFileModify(w http.ResponseWriter, instance FrpcInstance, modifiedData map[string]interface{}, username string) { func handleConfigFileModify(w http.ResponseWriter, instance FrpcInstance, modifiedData map[string]interface{}, username string) {
configPath := instance.ConfigPath configPath := instance.ConfigPath
// Read current config file content
configContent, err := os.ReadFile(configPath) configContent, err := os.ReadFile(configPath)
if err != nil { if err != nil {
postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to read config file %s: %v", configPath, err)) postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to read config file %s: %v", configPath, err))
@@ -402,7 +390,6 @@ func handleConfigFileModify(w http.ResponseWriter, instance FrpcInstance, modifi
return return
} }
// Parse config file content
updatedConfig, err := updateCommonSection(string(configContent), modifiedData) updatedConfig, err := updateCommonSection(string(configContent), modifiedData)
if err != nil { if err != nil {
postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to update common section: %v", err)) postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to update common section: %v", err))
@@ -410,14 +397,12 @@ func handleConfigFileModify(w http.ResponseWriter, instance FrpcInstance, modifi
return return
} }
// Write updated config file content back to file
if err := os.WriteFile(configPath, []byte(updatedConfig), 0644); err != nil { if err := os.WriteFile(configPath, []byte(updatedConfig), 0644); err != nil {
postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to write config file %s: %v", configPath, err)) postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to write config file %s: %v", configPath, err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to write config file") SendErrorResponse(w, http.StatusInternalServerError, "Failed to write config file")
return return
} }
// Update instance fields in database
if v, ok := modifiedData["server_addr"].(string); ok && v != "" { if v, ok := modifiedData["server_addr"].(string); ok && v != "" {
instance.ServerAddr = v instance.ServerAddr = v
} }
@@ -443,44 +428,23 @@ func handleConfigFileModify(w http.ResponseWriter, instance FrpcInstance, modifi
} }
func updateCommonSection(configContent string, modifiedData map[string]interface{}) (string, error) { func updateCommonSection(configContent string, modifiedData map[string]interface{}) (string, error) {
cfg, err := ini.Load([]byte(configContent)) var config FrpcConfig
if err != nil { if _, err := toml.Decode(configContent, &config); err != nil {
return "", fmt.Errorf("failed to parse config: %w", err) return "", fmt.Errorf("failed to parse config: %w", err)
} }
commonSection := cfg.Section("common")
if commonSection == nil {
return "", fmt.Errorf("common section not found")
}
for key, value := range modifiedData { for key, value := range modifiedData {
commonSection.Key(key).SetValue(formatConfigValue(value)) config.Common[key] = value
} }
var buf strings.Builder var buf strings.Builder
if _, err := cfg.WriteTo(&buf); err != nil { if err := toml.NewEncoder(&buf).Encode(config); err != nil {
return "", fmt.Errorf("failed to write config: %w", err) return "", fmt.Errorf("failed to write config: %w", err)
} }
return buf.String(), nil return buf.String(), nil
} }
func formatConfigValue(value interface{}) string {
switch v := value.(type) {
case string:
return v
case bool:
return fmt.Sprintf("%t", v)
case float64:
if v == float64(int64(v)) {
return fmt.Sprintf("%d", int64(v))
}
return fmt.Sprintf("%f", v)
default:
return fmt.Sprintf("%v", v)
}
}
func handleSystemConfigModify(w http.ResponseWriter, r *http.Request, instance FrpcInstance, modifiedData map[string]interface{}, user *User) { func handleSystemConfigModify(w http.ResponseWriter, r *http.Request, instance FrpcInstance, modifiedData map[string]interface{}, user *User) {
newName := instance.Name newName := instance.Name
newRunUser := instance.RunUser newRunUser := instance.RunUser
@@ -501,7 +465,6 @@ func handleSystemConfigModify(w http.ResponseWriter, r *http.Request, instance F
oldConfigPath := instance.ConfigPath oldConfigPath := instance.ConfigPath
var newConfigPath string var newConfigPath string
// If instance name or run user changed, need to rename config file
if newName != instance.Name || newRunUser != instance.RunUser { if newName != instance.Name || newRunUser != instance.RunUser {
configDir, err := GetConfigDir() configDir, err := GetConfigDir()
if err != nil { if err != nil {
@@ -526,7 +489,6 @@ func handleSystemConfigModify(w http.ResponseWriter, r *http.Request, instance F
newConfigPath = oldConfigPath newConfigPath = oldConfigPath
} }
// Update instance fields in database
instance.Name = newName instance.Name = newName
instance.RunUser = newRunUser instance.RunUser = newRunUser
instance.BootAtStart = newBootAtStart instance.BootAtStart = newBootAtStart
@@ -538,7 +500,6 @@ func handleSystemConfigModify(w http.ResponseWriter, r *http.Request, instance F
return return
} }
// Handle boot service creation and removal
if oldBootAtStart && !newBootAtStart { if oldBootAtStart && !newBootAtStart {
if err := removeBootService(user.Username, instance.Name); err != nil { if err := removeBootService(user.Username, instance.Name); err != nil {
postLog.Error(fmt.Sprintf("[handleSystemConfigModify] Failed to remove boot service: %v", err)) postLog.Error(fmt.Sprintf("[handleSystemConfigModify] Failed to remove boot service: %v", err))
@@ -574,78 +535,27 @@ func handleSystemConfigModify(w http.ResponseWriter, r *http.Request, instance F
data["bootServiceError"] = bootServiceError data["bootServiceError"] = bootServiceError
} }
SendSuccessResponse(w, "System config modified successfully", data) SendSuccessResponse(w, "System config modified successfully", data)
postLog.Info(fmt.Sprintf("[handleSystemConfigModify] System config for instance %s modified successfully: bootAtStart=%v, runUser=%s", newName, newBootAtStart, newRunUser))
}
func ListInstancesHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
SendErrorResponse(w, http.StatusMethodNotAllowed, "Invalid request method")
return
}
userID, _, err := ValidateRequestWithHeader(w, r)
if err != nil {
postLog.Error(fmt.Sprintf("[ListInstancesHandler] Failed to validate request: %v", err))
SendErrorResponse(w, http.StatusUnauthorized, "Failed to validate request")
return
}
userType, err := GetUserType(userID)
if err != nil {
postLog.Error(fmt.Sprintf("[ListInstancesHandler] Failed to get user type: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to get user type")
return
}
instanceList, err := DBListFrpcInstances()
if err != nil {
postLog.Error(fmt.Sprintf("[ListInstancesHandler] Failed to query instances: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to query instances")
return
}
var responseInstances []map[string]interface{}
for _, instance := range instanceList {
instanceData := map[string]interface{}{
"instanceID": instance.ID,
"name": instance.Name,
"serverAddr": instance.ServerAddr,
"serverPort": instance.ServerPort,
"auth_method": instance.AuthMethod,
"bootAtStart": instance.BootAtStart,
"runUser": instance.RunUser,
"configPath": instance.ConfigPath,
"createdAt": instance.CreatedAt,
"createdBy": instance.CreatedBy,
}
if userType == "visitor" {
delete(instanceData, "serverAddr")
delete(instanceData, "serverPort")
delete(instanceData, "auth_method")
}
responseInstances = append(responseInstances, instanceData)
}
if responseInstances == nil {
responseInstances = []map[string]interface{}{}
}
SendSuccessResponse(w, "Instances retrieved successfully", responseInstances)
} }
func generateFrpcConfig(info InstanceInfo) string { func generateFrpcConfig(info InstanceInfo) string {
var sb strings.Builder config := FrpcConfig{
sb.WriteString("[common]\n") Common: make(map[string]interface{}),
sb.WriteString(fmt.Sprintf("server_addr = %s\n", info.ServerAddr))
sb.WriteString(fmt.Sprintf("server_port = %s\n", info.ServerPort))
sb.WriteString(fmt.Sprintf("auth_method = %s\n", info.AuthMethod))
for key, value := range info.Additional {
sb.WriteString(fmt.Sprintf("%s = %v\n", key, value))
} }
sb.WriteString("\n")
return sb.String() config.Common["server_addr"] = info.ServerAddr
config.Common["server_port"] = info.ServerPort
config.Common["auth_method"] = info.AuthMethod
for key, value := range info.Additional {
config.Common[key] = value
}
var buf strings.Builder
if err := toml.NewEncoder(&buf).Encode(config); err != nil {
return ""
}
return buf.String()
} }
func GetUserInstances(userID int) ([]FrpcInstance, error) { func GetUserInstances(userID int) ([]FrpcInstance, error) {
@@ -681,3 +591,56 @@ func getStringFromMap(m map[string]interface{}, key string) string {
} }
return "" return ""
} }
func ListInstancesHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
SendErrorResponse(w, http.StatusMethodNotAllowed, "Invalid request method")
postLog.Debug(fmt.Sprintf("[ListInstancesHandler] Invalid request method: %s", r.Method))
return
}
userID, _, err := ValidateRequestWithHeader(w, r)
if err != nil {
postLog.Error(fmt.Sprintf("[ListInstancesHandler] Failed to validate request header: %v", err))
SendErrorResponse(w, http.StatusBadRequest, "Invalid request header")
return
}
userType, err := GetUserType(userID)
if err != nil {
postLog.Error(fmt.Sprintf("[ListInstancesHandler] Failed to get user type: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to get user type")
return
}
instances, err := GetUserInstances(userID)
if err != nil {
postLog.Error(fmt.Sprintf("[ListInstancesHandler] Failed to get user instances: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to get instances")
return
}
instanceList := make([]map[string]interface{}, len(instances))
for i, inst := range instances {
instanceData := map[string]interface{}{
"instanceID": inst.ID,
"name": inst.Name,
"bootAtStart": inst.BootAtStart,
"runUser": inst.RunUser,
"configPath": inst.ConfigPath,
"createdAt": inst.CreatedAt,
"createdBy": inst.CreatedBy,
}
if userType == "admin" || userType == "superuser" {
instanceData["serverAddr"] = inst.ServerAddr
instanceData["serverPort"] = inst.ServerPort
instanceData["auth_method"] = inst.AuthMethod
}
instanceList[i] = instanceData
}
SendSuccessResponse(w, "Instances retrieved successfully", instanceList)
postLog.Info(fmt.Sprintf("[ListInstancesHandler] Retrieved %d instances for user %d (type: %s)", len(instances), userID, userType))
}
+62 -33
View File
@@ -3,6 +3,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/BurntSushi/toml"
"io" "io"
"net/http" "net/http"
"os" "os"
@@ -106,8 +107,12 @@ func CreateProxyHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
proxyConfig := addFrpcProxy(proxyInfo) updatedContent, err := addFrpcProxy(string(configContent), proxyInfo)
updatedContent := string(configContent) + proxyConfig if err != nil {
postLog.Error(fmt.Sprintf("[CreateProxyHandler] Failed to add proxy: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to add proxy")
return
}
if err := os.WriteFile(instance.ConfigPath, []byte(updatedContent), 0644); err != nil { if err := os.WriteFile(instance.ConfigPath, []byte(updatedContent), 0644); err != nil {
postLog.Error(fmt.Sprintf("[CreateProxyHandler] Failed to write config file %s: %v", instance.ConfigPath, err)) postLog.Error(fmt.Sprintf("[CreateProxyHandler] Failed to write config file %s: %v", instance.ConfigPath, err))
@@ -124,16 +129,28 @@ func CreateProxyHandler(w http.ResponseWriter, r *http.Request) {
postLog.Info(fmt.Sprintf("[CreateProxyHandler] Proxy %s created successfully for instance %s", proxyInfo.Name, instance.Name)) postLog.Info(fmt.Sprintf("[CreateProxyHandler] Proxy %s created successfully for instance %s", proxyInfo.Name, instance.Name))
} }
func addFrpcProxy(info FrpcProxyInfo) string { func addFrpcProxy(configContent string, info FrpcProxyInfo) (string, error) {
var sb strings.Builder var config FrpcConfig
sb.WriteString("\n[[proxies]]\n") if _, err := toml.Decode(configContent, &config); err != nil {
sb.WriteString(fmt.Sprintf("name = %s\n", info.Name)) return "", fmt.Errorf("failed to parse config: %w", err)
sb.WriteString(fmt.Sprintf("type = %s\n", info.Type)) }
sb.WriteString(fmt.Sprintf("local_ip = %s\n", info.LocalIP))
sb.WriteString(fmt.Sprintf("local_port = %s\n", info.LocalPort))
sb.WriteString(fmt.Sprintf("remote_port = %s\n", info.RemotePort))
return sb.String() proxy := map[string]interface{}{
"name": info.Name,
"type": info.Type,
"local_ip": info.LocalIP,
"local_port": info.LocalPort,
"remote_port": info.RemotePort,
}
config.Proxies = append(config.Proxies, proxy)
var buf strings.Builder
if err := toml.NewEncoder(&buf).Encode(config); err != nil {
return "", fmt.Errorf("failed to write config: %w", err)
}
return buf.String(), nil
} }
func DeleteProxyHandler(w http.ResponseWriter, r *http.Request) { func DeleteProxyHandler(w http.ResponseWriter, r *http.Request) {
@@ -211,31 +228,13 @@ func DeleteProxyHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
lines := strings.Split(string(configContent), "\n") updatedContent, err := removeFrpcProxy(string(configContent), proxyName)
var newLines []string if err != nil {
var i int postLog.Error(fmt.Sprintf("[DeleteProxyHandler] Failed to remove proxy: %v", err))
for i < len(lines) { SendErrorResponse(w, http.StatusInternalServerError, "Failed to remove proxy")
if strings.HasPrefix(lines[i], "[[proxies]]") {
nameLine := i + 1
if nameLine < len(lines) && strings.HasPrefix(lines[nameLine], "name = ") {
currentProxyName := strings.TrimSpace(strings.TrimPrefix(lines[nameLine], "name = "))
if currentProxyName == proxyName {
i += 6
continue
}
}
}
newLines = append(newLines, lines[i])
i++
}
if len(newLines) == len(lines) {
postLog.Error(fmt.Sprintf("[DeleteProxyHandler] Proxy %s not found in config file %s", proxyName, instance.ConfigPath))
SendErrorResponse(w, http.StatusNotFound, "Proxy not found")
return return
} }
updatedContent := strings.Join(newLines, "\n")
if err := os.WriteFile(instance.ConfigPath, []byte(updatedContent), 0644); err != nil { if err := os.WriteFile(instance.ConfigPath, []byte(updatedContent), 0644); err != nil {
postLog.Error(fmt.Sprintf("[DeleteProxyHandler] Failed to write config file %s: %v", instance.ConfigPath, err)) postLog.Error(fmt.Sprintf("[DeleteProxyHandler] Failed to write config file %s: %v", instance.ConfigPath, err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to write config file") SendErrorResponse(w, http.StatusInternalServerError, "Failed to write config file")
@@ -250,3 +249,33 @@ func DeleteProxyHandler(w http.ResponseWriter, r *http.Request) {
}) })
postLog.Info(fmt.Sprintf("[DeleteProxyHandler] Proxy %s deleted successfully from instance %s", proxyName, instance.Name)) postLog.Info(fmt.Sprintf("[DeleteProxyHandler] Proxy %s deleted successfully from instance %s", proxyName, instance.Name))
} }
func removeFrpcProxy(configContent string, proxyName string) (string, error) {
var config FrpcConfig
if _, err := toml.Decode(configContent, &config); err != nil {
return "", fmt.Errorf("failed to parse config: %w", err)
}
var found bool
var newProxies []map[string]interface{}
for _, proxy := range config.Proxies {
if name, ok := proxy["name"].(string); ok && name == proxyName {
found = true
continue
}
newProxies = append(newProxies, proxy)
}
if !found {
return "", fmt.Errorf("proxy %s not found", proxyName)
}
config.Proxies = newProxies
var buf strings.Builder
if err := toml.NewEncoder(&buf).Encode(config); err != nil {
return "", fmt.Errorf("failed to write config: %w", err)
}
return buf.String(), nil
}
+6 -4
View File
@@ -2,18 +2,20 @@ module super-frpc
go 1.24.0 go 1.24.0
require modernc.org/sqlite v1.46.1 require (
github.com/BurntSushi/toml v1.4.0
github.com/gorilla/websocket v1.5.3
golang.org/x/sys v0.37.0
modernc.org/sqlite v1.46.1
)
require ( require (
github.com/dustin/go-humanize v1.0.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
golang.org/x/sys v0.37.0 // indirect
gopkg.in/ini.v1 v1.67.1 // indirect
modernc.org/libc v1.67.6 // indirect modernc.org/libc v1.67.6 // indirect
modernc.org/mathutil v1.7.1 // indirect modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect modernc.org/memory v1.11.0 // indirect
+32 -18
View File
@@ -1,43 +1,57 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk=
github.com/mattn/go-sqlite3 v1.14.34/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY= golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70= golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
gopkg.in/ini.v1 v1.67.1 h1:tVBILHy0R6e4wkYOn3XmiITt/hEVH4TFMYvAX2Ytz6k= golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
gopkg.in/ini.v1 v1.67.1/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss= modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc=
modernc.org/ccgo/v4 v4.30.1/go.mod h1:bIOeI1JL54Utlxn+LwrFyjCx2n2RDiYEaJVSrgdrRfM=
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.1 h1:k8T3gkXWY9sEiytKhcgyiZ2L0DTyCQ/nvX+LoCljoRE=
modernc.org/gc/v3 v3.1.1/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.67.6 h1:eVOQvpModVLKOdT+LvBPjdQqfrZq+pC39BygcT+E7OI= modernc.org/libc v1.67.6 h1:eVOQvpModVLKOdT+LvBPjdQqfrZq+pC39BygcT+E7OI=
modernc.org/libc v1.67.6/go.mod h1:JAhxUVlolfYDErnwiqaLvUqc8nfb2r6S6slAgZOnaiE= modernc.org/libc v1.67.6/go.mod h1:JAhxUVlolfYDErnwiqaLvUqc8nfb2r6S6slAgZOnaiE=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.46.1 h1:eFJ2ShBLIEnUWlLy12raN0Z1plqmFX9Qe3rjQTKt6sU= modernc.org/sqlite v1.46.1 h1:eFJ2ShBLIEnUWlLy12raN0Z1plqmFX9Qe3rjQTKt6sU=
modernc.org/sqlite v1.46.1/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA= modernc.org/sqlite v1.46.1/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=