You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.3 KiB
Go

package main
import (
"fmt"
"log"
"github.com/gin-gonic/gin"
socketio "github.com/googollee/go-socket.io"
2 years ago
eventemitter "github.com/hyperzlib/go-event-emitter"
"github.com/hyperzlib/isekai-remote-playback/context"
"github.com/hyperzlib/isekai-remote-playback/middleware"
"github.com/hyperzlib/isekai-remote-playback/routes"
"github.com/hyperzlib/isekai-remote-playback/store"
"github.com/spf13/viper"
)
func initConfig() {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.SetDefault("debug", true)
viper.SetDefault("http.baseurl", "")
viper.SetDefault("http.listen", "0.0.0.0")
viper.SetDefault("http.port", 8913)
viper.SetDefault("http.origins", []string{})
viper.SetDefault("redis.prefix", "irp")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error config file: %w", err))
}
}
func main() {
ctx := context.NewServerContext()
initConfig()
// 初始化存储
store.InitStore()
// 创建事件系统
ctx.EventSource = eventemitter.NewEmitter(true)
// Socket.IO服务器
sockets := socketio.NewServer(nil)
ctx.Sockets = sockets
if viper.GetString("redis.addr") != "" {
_, err := sockets.Adapter(&socketio.RedisAdapterOptions{
Addr: viper.GetString("redis.addr"),
Prefix: viper.GetString("redis.prefix"),
Password: viper.GetString("redis.password"),
Network: viper.GetString("redis.network"),
})
if err != nil {
log.Fatalf("socket.io redis adaper error: %s\n", err)
}
}
sockets, err := routes.CreateSocketRouter(sockets, ctx)
if err != nil {
log.Fatal("Cannot create websocket httpApp", err)
}
go func() {
if err := sockets.Serve(); err != nil {
log.Fatalf("socket.io listen error: %s\n", err)
}
}()
defer sockets.Close()
// HTTP服务器
httpApp := gin.New()
ctx.HttpServer = httpApp
httpApp.Use(middleware.Handler)
httpApp.Use(middleware.CORSMiddleware(viper.GetStringSlice("http.origins")))
httpApp.GET("/socket.io/*any", gin.WrapH(sockets))
httpApp.POST("/socket.io/*any", gin.WrapH(sockets))
httpApp = routes.CreateWebRouter(httpApp)
if viper.GetBool("debug") {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
hostAddr := viper.GetString("http.listen") + ":" + viper.GetString("http.port")
if err := httpApp.Run(hostAddr); err != nil {
log.Fatal("failed run app: ", err)
}
}