hostSync/cmd/add.go

67 lines
1.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cmd
import (
"os"
"github.com/evil7/hostsync/core"
"github.com/evil7/hostsync/utils"
"github.com/spf13/cobra"
)
// addCmd 添加命令
var addCmd = &cobra.Command{
Use: "add <blockName> <domain> [ip]",
Short: "添加域名记录",
Long: `添加域名记录到指定块。如果不存在该块则会自动创建。
如果不指定IP地址将自动解析域名。
示例:
hostsync add github github.com 140.82.114.3 # 指定IP添加
hostsync add github api.github.com # 自动解析IP添加`,
Args: cobra.RangeArgs(2, 3),
Run: runAdd,
}
func runAdd(cmd *cobra.Command, args []string) {
utils.CheckAdmin()
blockName := args[0]
domain := args[1]
var ip string
if !utils.ValidateBlockName(blockName) {
utils.LogError("无效的块名称: %s", blockName)
utils.LogInfo("块名称只能包含字母、数字、下划线和连字符")
os.Exit(1)
}
hm := core.NewHostsManager()
if err := hm.Load(); err != nil {
utils.LogError("加载hosts文件失败: %v", err)
os.Exit(1)
}
if len(args) == 3 {
// 使用指定的IP
ip = args[2]
} else {
// 自动解析IP
utils.LogInfo("正在解析域名: %s", domain)
resolver := core.NewDNSResolver()
var err error
ip, err = resolver.ResolveDomain(domain, "", "")
if err != nil {
utils.LogError("解析域名失败: %v", err)
os.Exit(1)
}
utils.LogSuccess("解析成功: %s -> %s", domain, ip)
}
if err := hm.AddEntry(blockName, domain, ip); err != nil {
utils.LogError("添加记录失败: %v", err)
os.Exit(1)
}
utils.LogSuccess("已添加记录: %s -> %s (块: %s)", domain, ip, blockName)
}