feat(instance): refactor modify endpoint to support config types

- Change modify endpoint from `/modify/{field}` to `/modify` with POST
- Add support for two modification types: configFile and systemConfig
- Implement config file parsing using ini package for configFile type
- Update database schema to include name in update query
- Add comprehensive input validation and error handling
- Update documentation to reflect new API changes
This commit is contained in:
2026-03-02 22:43:18 +08:00
parent a46a564d96
commit 760a82f86e
7 changed files with 257 additions and 85 deletions
+167 -65
View File
@@ -13,6 +13,8 @@ import (
"strings"
"super-frpc/postLog"
"time"
"gopkg.in/ini.v1"
)
type InstanceInfo struct {
@@ -307,7 +309,7 @@ func DeleteInstanceHandler(w http.ResponseWriter, r *http.Request) {
postLog.Info(fmt.Sprintf("[DeleteInstanceHandler] Instance %s deleted successfully", instanceName))
}
func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request, field string) {
func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
postLog.Error(fmt.Sprintf("[ModifyInstanceHandler] Invalid request method: %s", r.Method))
SendErrorResponse(w, http.StatusMethodNotAllowed, "Invalid request method")
@@ -335,6 +337,29 @@ func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request, field string)
return
}
instanceID := getStringFromMap(reqMap, "instanceID")
if instanceID == "" {
SendErrorResponse(w, http.StatusBadRequest, "instanceID is required")
return
}
modifyType := getStringFromMap(reqMap, "type")
if modifyType == "" {
SendErrorResponse(w, http.StatusBadRequest, "type is required")
return
}
if modifyType != "configFile" && modifyType != "systemConfig" { // Detect valid modify type
SendErrorResponse(w, http.StatusBadRequest, "type must be 'configFile' or 'systemConfig'")
return
}
modifiedData, ok := reqMap["modifiedData"].(map[string]interface{})
if !ok || modifiedData == nil {
SendErrorResponse(w, http.StatusBadRequest, "modifiedData is required and must be an object")
return
}
// 从Header中验证token和timeStamp
userID, _, err := ValidateRequestWithHeader(w, r)
if err != nil {
@@ -356,14 +381,7 @@ func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request, field string)
return
}
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 {
postLog.Error(fmt.Sprintf("[ModifyInstanceHandler] User %d tried to modify a not existed instance: %s", userID, instanceName))
SendErrorResponse(w, http.StatusNotFound, "Instance not found")
@@ -375,38 +393,133 @@ func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request, field string)
return
}
// 验证 instanceID 是否匹配
if fmt.Sprintf("%d", instance.ID) != instanceID {
SendErrorResponse(w, http.StatusBadRequest, "instanceID does not match instanceName")
return
}
if modifyType == "configFile" {
handleConfigFileModify(w, instance, modifiedData, user.Username)
} else {
handleSystemConfigModify(w, r, instance, modifiedData, user)
}
}
func handleConfigFileModify(w http.ResponseWriter, instance FrpcInstance, modifiedData map[string]interface{}, username string) {
configPath := instance.ConfigPath
// Read current config file content
configContent, err := os.ReadFile(configPath)
if err != nil {
postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to read config file %s: %v", configPath, err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to read config file")
return
}
// Parse config file content
updatedConfig, err := updateCommonSection(string(configContent), modifiedData)
if err != nil {
postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to update common section: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to update config file")
return
}
// Write updated config file content back to file
if err := os.WriteFile(configPath, []byte(updatedConfig), 0644); err != nil {
postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to write config file %s: %v", configPath, err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to write config file")
return
}
// Update instance fields in database
if v, ok := modifiedData["server_addr"].(string); ok && v != "" {
instance.ServerAddr = v
}
if v, ok := modifiedData["server_port"].(string); ok && v != "" {
instance.ServerPort = v
}
if v, ok := modifiedData["auth_method"].(string); ok && v != "" {
instance.AuthMethod = v
}
if err := DBUpdateFrpcInstance(instance); err != nil {
postLog.Error(fmt.Sprintf("[handleConfigFileModify] Failed to update instance in database: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to update instance in database")
return
}
SendSuccessResponse(w, "Config file modified successfully", map[string]interface{}{
"instanceName": instance.Name,
"instanceID": instance.ID,
"configPath": configPath,
})
postLog.Info(fmt.Sprintf("[handleConfigFileModify] Config file for instance %s modified successfully", instance.Name))
}
func updateCommonSection(configContent string, modifiedData map[string]interface{}) (string, error) {
cfg, err := ini.Load([]byte(configContent))
if err != nil {
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 {
commonSection.Key(key).SetValue(formatConfigValue(value))
}
var buf strings.Builder
if _, err := cfg.WriteTo(&buf); err != nil {
return "", fmt.Errorf("failed to write config: %w", err)
}
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) {
newName := instance.Name
newServerAddr := instance.ServerAddr
newServerPort := instance.ServerPort
newAuthMethod := instance.AuthMethod
newRunUser := instance.RunUser
newBootAtStart := instance.BootAtStart
oldBootAtStart := instance.BootAtStart
if v, ok := reqMap["name"].(string); ok && v != "" {
if v, ok := modifiedData["name"].(string); ok && v != "" {
newName = v
}
if v, ok := reqMap["serverAddr"].(string); ok && v != "" {
newServerAddr = v
}
if v, ok := reqMap["serverPort"].(string); ok && v != "" {
newServerPort = v
}
if v, ok := reqMap["auth_method"].(string); ok && v != "" {
newAuthMethod = v
}
if v, ok := reqMap["runUser"].(string); ok && v != "" {
if v, ok := modifiedData["runUser"].(string); ok {
newRunUser = v
}
if v, ok := reqMap["bootAtStart"].(bool); ok {
if v, ok := modifiedData["bootAtStart"].(bool); ok {
newBootAtStart = v
}
oldConfigPath := instance.ConfigPath
var newConfigPath string
// If instance name or run user changed, need to rename config file
if newName != instance.Name || newRunUser != instance.RunUser {
configDir, err := GetConfigDir()
if err != nil {
postLog.Error(fmt.Sprintf("[ModifyInstanceHandler] Failed to get config directory: %v", err))
postLog.Error(fmt.Sprintf("[handleSystemConfigModify] Failed to get config directory: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to get config directory")
return
}
@@ -417,7 +530,7 @@ func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request, field string)
if oldConfigPath != newConfigPath {
if _, err := os.Stat(oldConfigPath); err == nil {
if err := os.Rename(oldConfigPath, newConfigPath); err != nil {
postLog.Error(fmt.Sprintf("[ModifyInstanceHandler] Failed to rename config file %s to %s: %v", oldConfigPath, newConfigPath, err))
postLog.Error(fmt.Sprintf("[handleSystemConfigModify] Failed to rename config file %s to %s: %v", oldConfigPath, newConfigPath, err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to rename config file")
return
}
@@ -427,55 +540,44 @@ func ModifyInstanceHandler(w http.ResponseWriter, r *http.Request, field string)
newConfigPath = oldConfigPath
}
info := InstanceInfo{
Name: newName,
ServerAddr: newServerAddr,
ServerPort: newServerPort,
AuthMethod: newAuthMethod,
RunUser: newRunUser,
}
configContent := generateFrpcConfig(info)
if err := os.WriteFile(newConfigPath, []byte(configContent), 0644); err != nil {
postLog.Error(fmt.Sprintf("[ModifyInstanceHandler] Failed to update config file: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to update config file")
return
}
// _, err = frpcDB.Exec(`
// UPDATE frpcInstances
// SET name = ?, serverAddr = ?, serverPort = ?, auth_method = ?, bootAtStart = ?, runUser = ?, configPath = ?
// WHERE id = ?
// `, newName, newServerAddr, newServerPort, newAuthMethod, newBootAtStart, newRunUser, newConfigPath, instance.ID)
// Update instance fields in database
instance.Name = newName
instance.ServerAddr = newServerAddr
instance.ServerPort = newServerPort
instance.AuthMethod = newAuthMethod
instance.BootAtStart = newBootAtStart
instance.RunUser = newRunUser
instance.BootAtStart = newBootAtStart
instance.ConfigPath = newConfigPath
err = DBUpdateFrpcInstance(instance)
if err != nil {
postLog.Error(fmt.Sprintf("[ModifyInstanceHandler] Failed to update instance in database: %v", err))
if err := DBUpdateFrpcInstance(instance); err != nil {
postLog.Error(fmt.Sprintf("[handleSystemConfigModify] Failed to update instance in database: %v", err))
SendErrorResponse(w, http.StatusInternalServerError, "Failed to update instance in database")
return
}
if instance.BootAtStart && !newBootAtStart {
removeBootService(user.Username, instanceName)
} else if !instance.BootAtStart && newBootAtStart {
createBootService(user.Username, newName, newConfigPath, newRunUser)
} else if instance.BootAtStart && newBootAtStart && (instance.Name != newName || instance.RunUser != newRunUser) {
removeBootService(user.Username, instanceName)
createBootService(user.Username, newName, newConfigPath, newRunUser)
// Handle boot service creation and removal
if oldBootAtStart && !newBootAtStart {
if err := removeBootService(user.Username, instance.Name); err != nil {
postLog.Error(fmt.Sprintf("[handleSystemConfigModify] Failed to remove boot service: %v", err))
}
} else if !oldBootAtStart && newBootAtStart {
if err := createBootService(user.Username, newName, newConfigPath, newRunUser); err != nil {
postLog.Error(fmt.Sprintf("[handleSystemConfigModify] Failed to create boot service: %v", err))
}
} else if oldBootAtStart && newBootAtStart && (instance.Name != newName || instance.RunUser != newRunUser) {
if err := removeBootService(user.Username, instance.Name); err != nil {
postLog.Error(fmt.Sprintf("[handleSystemConfigModify] Failed to remove old boot service: %v", err))
}
if err := createBootService(user.Username, newName, newConfigPath, newRunUser); err != nil {
postLog.Error(fmt.Sprintf("[handleSystemConfigModify] Failed to create new boot service: %v", err))
}
}
SendSuccessResponse(w, "Instance modified successfully", map[string]interface{}{
"name": newName,
"configPath": newConfigPath,
SendSuccessResponse(w, "System config modified successfully", map[string]interface{}{
"instanceName": newName,
"instanceID": instance.ID,
"configPath": newConfigPath,
"bootAtStart": newBootAtStart,
"runUser": newRunUser,
})
postLog.Info(fmt.Sprintf("[ModifyInstanceHandler] Instance %s modified successfully: configPath=%s, bootAtStart=%v, runUser=%s", newName, newConfigPath, newBootAtStart, newRunUser))
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) {