Files
frpc-console/internal/frp/config.go
T

80 lines
1.4 KiB
Go

package frp
import (
"bytes"
_ "embed"
"os"
"text/template"
"frpc-console/internal/db"
)
//go:embed frpc.tmpl
var FrpcTemplateContent string
// ConfigData frpc.toml 模板渲染数据
type ConfigData struct {
*db.GlobalConfig
Proxies []db.Proxy
WireProtocolLine string
}
// GenerateConfig 生成 frpc.toml 配置文件
func GenerateConfig() error {
cfg, err := db.GetGlobalConfig()
if err != nil {
return err
}
proxies, err := db.GetProxies()
if err != nil {
return err
}
var activeProxies []db.Proxy
for _, p := range proxies {
if p.Enabled {
activeProxies = append(activeProxies, p)
}
}
data := ConfigData{
GlobalConfig: cfg,
Proxies: activeProxies,
}
if cfg.WireProtocolV2 {
data.WireProtocolLine = `wireProtocol = "v2"`
} else {
data.WireProtocolLine = ""
}
var tmplContent string
if _, err := os.Stat("frpc.tmpl"); err == nil {
content, readErr := os.ReadFile("frpc.tmpl")
if readErr == nil {
tmplContent = string(content)
} else {
tmplContent = FrpcTemplateContent
}
} else {
tmplContent = FrpcTemplateContent
}
tmpl, err := template.New("frpc").Parse(tmplContent)
if err != nil {
return err
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return err
}
if err := os.MkdirAll("./data", 0755); err != nil {
return err
}
return os.WriteFile("./data/frpc.toml", buf.Bytes(), 0644)
}