iptables-helper/internel/app/app.go

105 lines
2.5 KiB
Go

package app
import (
"encoding/json"
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/spf13/viper"
globalConf "iptables-helper/internel/conf"
"iptables-helper/internel/middleware"
"iptables-helper/internel/route"
"iptables-helper/pkg/config"
"iptables-helper/pkg/logger"
"iptables-helper/pkg/utils/command"
fib "iptables-helper/pkg/utils/fiber"
"strings"
"time"
)
var app *fiber.App
var conf = new(config.Conf)
func CreateApp(c *config.Conf) *fiber.App {
return fiber.New(fiber.Config{
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
Prefork: c.Server.PreFork,
CaseSensitive: c.Server.CaseSensitive,
StrictRouting: c.Server.StrictRouting,
ServerHeader: c.Server.ServerHeader,
ErrorHandler: route.GlobalErrorHandler(),
})
}
func Run() {
err := viper.Unmarshal(conf)
globalConf.Conf = conf
if err != nil {
logger.Log().Fatalf("配置文件解析失败: %s, 请检查配置是否有误", err)
}
Shutdown()
// 初始化数据源
fib.Exec(func() {
InitApp(conf)
if !conf.Custom.UseCustomChain {
logger.Log().Infof("使用全局管理")
} else {
customChain := strings.TrimSpace(conf.Custom.CustomChain)
logger.Log().Infof("使用自定义链管理 (管理自定义链: %s)", customChain)
if len(customChain) > 0 {
commander := command.Commander{}
_, err := commander.ExecuteWithResult(fmt.Sprintf("sudo iptables -N %s", customChain))
if err == nil {
// 入口
commander.Execute(fmt.Sprintf("sudo iptables -A INPUT -j %s", customChain))
// 出口
commander.Execute(fmt.Sprintf("sudo iptables -A OUTPUT -j %s", customChain))
// 转发
commander.Execute(fmt.Sprintf("sudo iptables -A FORWARD -j %s", customChain))
}
} else {
logger.Log().Fatal("防火墙配置失败: 自定义链名称不能为空")
}
}
})
// 创建 fiber 服务器
app = CreateApp(conf)
middleware.UseCorsMiddleWare(app)
// 设置路由
route.SetupRoute(app, conf)
// 启动完成
app.Hooks().OnListen(func(_ fiber.ListenData) error {
fib.Exec(func() {
logger.Log().Info("[√] [服务启动完成]")
})
return nil
})
if err := app.Listen(conf.Server.Addr); err != nil {
logger.Log().Fatalf("[x] [Fiber] 致命错误: %s", err)
}
}
func InitApp(conf *config.Conf) {
}
func Shutdown() {
if app == nil {
return
}
fib.Exec(func() {
})
logger.Log().Info("关闭服务")
timeout := 5 * time.Second
err := app.ShutdownWithTimeout(timeout)
if err != nil {
logger.Log().Fatal(err)
}
}