Note HttpServer must be started after starting UdpServer, when log and config have been setup
(us *UdpServer, hc *HttpConfig)
| 42 | |
| 43 | // Note HttpServer must be started after starting UdpServer, when log and config have been setup |
| 44 | func (hs *HttpServer) Start(us *UdpServer, hc *HttpConfig) error { |
| 45 | hs.id = time.Now().Format("2006-01-02 15:04:05") |
| 46 | log.Info("==================================================") |
| 47 | log.Info("=== HttpServer (%s) started ===", hs.id) |
| 48 | log.Info("==================================================") |
| 49 | |
| 50 | hs.udpServer = us |
| 51 | |
| 52 | ipStr := hc.HttpListenIp |
| 53 | var netIP net.IP |
| 54 | if len(ipStr) > 0 { |
| 55 | netIP = net.ParseIP(ipStr) |
| 56 | if netIP == nil { |
| 57 | log.Error("http listen ip address is incorrect! using udp listening ip") |
| 58 | netIP = us.listenAddr.IP |
| 59 | } |
| 60 | } else { |
| 61 | netIP = net.IPv4zero // will both listen on ipv4 0.0.0.0:port and ipv6 [::]:port |
| 62 | } |
| 63 | |
| 64 | listenPort := us.listenAddr.Port // use the same port as udp server if HttpListenPort is not specified |
| 65 | if hc.HttpListenPort > 0 && hc.HttpListenPort < 65536 { |
| 66 | listenPort = hc.HttpListenPort |
| 67 | } |
| 68 | hs.listenAddr = &net.TCPAddr{ |
| 69 | IP: netIP, |
| 70 | Port: listenPort, |
| 71 | } |
| 72 | |
| 73 | hs.signals.stop = make(chan struct{}) |
| 74 | |
| 75 | gin.SetMode(gin.ReleaseMode) |
| 76 | hs.ginEngine = gin.New() |
| 77 | store := cookie.NewStore([]byte("nhpstore")) |
| 78 | hs.ginEngine.Use(sessions.Sessions("nhpsessions", store)) |
| 79 | hs.ginEngine.Use(corsMiddleware()) |
| 80 | hs.ginEngine.Use(gin.LoggerWithWriter(us.log.Writer())) |
| 81 | hs.ginEngine.Use(gin.Recovery()) |
| 82 | |
| 83 | hs.initRouter() |
| 84 | |
| 85 | hs.httpServer = &http.Server{ |
| 86 | Addr: hs.listenAddr.String(), |
| 87 | Handler: hs.ginEngine, |
| 88 | ReadTimeout: time.Duration(hc.ReadTimeoutMs) * time.Millisecond, |
| 89 | WriteTimeout: time.Duration(hc.WriteTimeoutMs) * time.Millisecond, |
| 90 | IdleTimeout: time.Duration(hc.IdleTimeoutMs) * time.Millisecond, |
| 91 | } |
| 92 | |
| 93 | hs.wg.Add(1) |
| 94 | if hc.EnableTLS { |
| 95 | certFilePath := filepath.Join(ExeDirPath, hc.TLSCertFile) |
| 96 | keyFilePath := filepath.Join(ExeDirPath, hc.TLSKeyFile) |
| 97 | _, err1 := os.Stat(certFilePath) |
| 98 | _, err2 := os.Stat(keyFilePath) |
| 99 | if err1 == nil && err2 == nil { |
| 100 | go func() { |
| 101 | defer hs.wg.Done() |
no test coverage detected