// Copyright 2019 github.com. All rights reserved. // Use of this source code is governed by github.com. package main import ( "dust-monitor/handler/v1" "dust-monitor/parser" "dust-monitor/pb" "dust-monitor/tcp_packet" "dust-monitor/timetask" "flag" "fmt" "net" "net/http" "os" "log" "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" "dust-monitor/route" ) var ( configFile = flag.String("config", "conf/common.yaml", "config file location") version = flag.Bool("version", false, "print the version") GitCommit = "library-import" Version = "library-import" ) func showVersion() { fmt.Println("Version: ", Version) fmt.Println("GitCommit:", GitCommit) } func prepare(filename string) { // 加载配置 err := parser.LoadConfig(filename) if err != nil { fmt.Printf("get conf failed, err: %+v\n\n", err) os.Exit(1) } // 注册处理函数 // parser.Register(parser.MysqlHandler, parser.RedisHandler, parser.LoggerHandler) //parser.Register(parser.LoggerHandler, parser.MysqlHandler, parser.RedisHandler) parser.Register(parser.LoggerHandler, parser.MysqlHandler, parser.InfluxdbHandler) // 执行注册的处理函数 parser.Handle() v1.InitAreaCodeMap() // 建立rpc客户端 conns := pb.SetupClients() for _, conn := range conns { defer conn.Close() } timetask.Init() } func runDeviceTcp(ip string, port int) { service := fmt.Sprintf("%s:%d", ip, port) tcpAddr, err := net.ResolveTCPAddr("tcp4", service) if err != nil { fmt.Println("resolve tcp addr err:", err) os.Exit(1) } listener, err := net.ListenTCP("tcp", tcpAddr) if err != nil { fmt.Println("listen tcp err:", err) os.Exit(2) } for { fmt.Printf("listen:%v\n", listener.Addr().String()) conn, err := listener.Accept() if err != nil { continue } go tcp_packet.HandleSocketClient(conn) } } func runHttp() { // 新建engine engine := gin.New() handlers := gin.HandlersChain{} // 根据env_mode设置gin的运行模式 switch parser.Conf.RunMode { case "test": gin.SetMode(gin.TestMode) case "prod": gin.SetMode(gin.ReleaseMode) case "dev": fallthrough default: gin.SetMode(gin.DebugMode) // 根据配置是否生成swagger engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) // 输出打印日志 handlers = append(handlers, gin.Logger()) } // 处理panic handlers = append(handlers, gin.Recovery()) engine.Use(handlers...) // 设定路由 route.SetupRoute(engine) // 建立rpc客户端 conns := pb.SetupClients() for _, conn := range conns { defer conn.Close() } // 创建监听服务 server := &http.Server{ Addr: fmt.Sprintf("%s:%d", parser.Conf.DustMonitor.GatewayIp, parser.Conf.DustMonitor.GatewayPort), Handler: engine, } // 开始监听 log.Printf("Listening and serving HTTP on %s\n", server.Addr) go func() { if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("HTTP server listen failed. err: %s\n", err.Error()) } }() } func main() { flag.Parse() if *version { showVersion() os.Exit(1) } prepare(*configFile) runHttp() runDeviceTcp(parser.Conf.DustMonitor.ServiceIp, parser.Conf.DustMonitor.ServicePort) return }