-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
186 lines (156 loc) · 5.53 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package main
import (
"embed"
"flag"
"io/fs"
"log"
"net/http"
"os"
"strconv"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
_ "github.com/jensborch/go-foosball/docs"
swaggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/jensborch/go-foosball/model"
"github.com/jensborch/go-foosball/resources"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// @title Go-foosball API
// @version 0.8
// @description Foosball tournament REST service.
// @BasePath /api
// React client static web server content.
//
//go:embed client/build
var client embed.FS
func main() {
var (
port uint
dbfile string
debug bool
)
flag.UintVar(&port, "port", 8080, "the port number")
flag.StringVar(&dbfile, "db", "foosball.db", "the database file")
flag.BoolVar(&debug, "debug", false, "enable debug")
flag.Parse()
log.Printf("Starting go-foosball on port %d using database %s", port, dbfile)
engine, _ := setupServer(dbfile, debug)
engine.Run(":" + strconv.FormatUint(uint64(port), 10))
}
func corsHandler() gin.HandlerFunc {
config := cors.DefaultConfig()
config.AllowAllOrigins = true
return cors.New(config)
}
func setupServer(dbfile string, debug bool) (*gin.Engine, *gorm.DB) {
var gormlog logger.Interface
if !debug {
gin.SetMode(gin.ReleaseMode)
gormlog = logger.Default.LogMode(logger.Warn)
} else {
gormlog = logger.Default.LogMode(logger.Info)
}
router := gin.Default()
router.Use(corsHandler())
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("gamewinner", resources.GameWinnerValidator)
} else {
panic("failed to add validator")
}
db, err := gorm.Open(sqlite.Open(dbfile), &gorm.Config{
Logger: gormlog,
})
if err != nil {
panic("failed to connect database")
}
sqliteDb, _ := db.DB()
sqliteDb.SetMaxOpenConns(1)
db.AutoMigrate(&model.Tournament{},
&model.TournamentTable{},
&model.Table{},
&model.Player{},
&model.TournamentPlayer{},
&model.Game{},
&model.TournamentPlayerHistory{})
api := router.Group("/api")
players := api.Group("/players")
players.GET("", resources.GetPlayers(db))
players.POST("", resources.PostPlayer(db))
players.POST("/", resources.PostPlayer(db))
players.GET("/:name", resources.GetPlayer("name", db))
players.DELETE("/:name", resources.DeletePlayer("name", db))
tables := api.Group("/tables")
tables.GET("", resources.GetTables(db))
tables.POST("", resources.PostTable(db))
tables.POST("/", resources.PostTable(db))
tables.GET("/:id", resources.GetTable("id", db))
//tables.DELETE("/:id", resources.DeleteTable("id", db))
tournaments := api.Group("/tournaments")
tournaments.GET("", resources.GetTournaments(db))
tournaments.POST("", resources.PostTournament(db))
tournaments.POST("/", resources.PostTournament(db))
tournaments.GET("/:id", resources.GetTournament("id", db))
tournaments.DELETE("/:id", resources.DeleteTournament("id", db))
tournaments.GET("/:id/players", resources.GetTournamentPlayes("id", db))
tournaments.POST("/:id/players", resources.PostTournamentPlayer("id", db))
tournaments.POST("/:id/players/", resources.PostTournamentPlayer("id", db))
tournaments.DELETE("/:id/players/:name", resources.DeleteTournamentPlayer("id", "name", db))
tournaments.DELETE("/:id/players", resources.DeleteAllTournamentPlayers("id", db))
//tournaments.GET("/:id/players/:name", resources.GetTournamentPlayer("id", "name", db))
tournaments.GET("/:id/players/:name/history", resources.GetTournamentPlayeHistory("id", "name", db))
tournaments.GET("/:id/history", resources.GetTournamentHistory("id", db))
tournaments.GET("/:id/tables", resources.GetTournamentTables("id", db))
tournaments.POST("/:id/tables", resources.PostTournamentTables("id", db))
tournaments.POST("/:id/tables/", resources.PostTournamentTables("id", db))
tournaments.DELETE("/:id/tables/:table", resources.DeleteTournamentTable("id", "table", db))
tournaments.POST("/:id/tables/:table/games", resources.PostGame("id", "table", db))
tournaments.POST("/:id/tables/:table/games/", resources.PostGame("id", "table", db))
tournaments.GET("/:id/games", resources.GetGamesInTournament("id", db))
//Actions
tournaments.GET("/:id/games/random", resources.GetRandomGames("id", db))
tournaments.GET("/:id/games/start", resources.GetGameStart("id", db))
//Events
tournaments.GET("/:id/events/player", resources.GetPlayerEvents("id"))
tournaments.GET("/:id/events/game", resources.GetGameEvents("id"))
games := api.Group("/games")
games.GET("", resources.GetGames(db))
games.GET("/:id", resources.GetGame("id", db))
const avatars = "./avatars"
_, err = os.Stat(avatars)
if os.IsNotExist(err) {
err = os.Mkdir(avatars, 0755)
if err != nil {
panic("unable to create avatars foler")
}
}
router.Static("/avatars", avatars)
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
router.GET("/", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "/client")
})
subfs := subFs(client, "/client/", "client/build")
router.GET("/client/*any", func(c *gin.Context) {
serveStatic(c, subfs, "/client/")
})
return router, db
}
func serveStatic(c *gin.Context, f fs.FS, prefix string) {
p := c.Request.URL.Path[len(prefix):len(c.Request.URL.Path)]
if _, error := f.Open(p); error == nil {
c.FileFromFS(p, http.FS(f))
} else {
c.FileFromFS("/", http.FS(f))
}
}
func subFs(f fs.FS, prefix string, dir string) fs.FS {
subfs, err := fs.Sub(f, dir)
if err != nil {
panic(err)
}
return subfs
}