-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
74 lines (62 loc) · 2.33 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
package main
import (
"game-stats-api/pkg/database"
"game-stats-api/pkg/server"
"log"
"net/http"
"os"
"time"
_ "game-stats-api/docs"
"github.com/go-chi/chi/middleware"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
httpSwagger "github.com/swaggo/http-swagger"
)
// @Title Game Stats API
// @Version 1.0
// @License.name MIT
// @License.url https://opensource.org/licenses/MIT
// @BasePath /api/v1
func main() {
godotenv.Load()
address := os.Getenv("ADDRESS")
if address == "" {
address = "127.0.0.1"
}
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
err := database.Initialize("data.db")
if err != nil {
log.Println(err)
os.Exit(1)
}
router := mux.NewRouter()
router.StrictSlash(true)
router.HandleFunc("/api/v1/games/", server.CreateGameHandler).Methods("POST")
router.HandleFunc("/api/v1/games/", server.GetAllGamesHandler).Methods("GET")
router.HandleFunc("/api/v1/games/{id:[0-9]+}/", server.GetGameHandler).Methods("GET")
router.HandleFunc("/api/v1/games/{id:[0-9]+}/", server.DeleteGameHandler).Methods("DELETE")
router.HandleFunc("/api/v1/games/{id:[0-9]+}/players/", server.CreateGamePlayerHandler).Methods("POST")
router.HandleFunc("/api/v1/games/{gid:[0-9]+}/players/{pid:[0-9]+}/", server.DeleteGamePlayerHandler).Methods("DELETE")
router.HandleFunc("/api/v1/games/{gid:[0-9]+}/players/{pid:[0-9]+}/stats/", server.AddGamePlayerStatHandler).Methods("POST")
router.HandleFunc("/api/v1/games/{gid:[0-9]+}/players/{pid:[0-9]+}/laststat/", server.DeleteGamePlayerLastStatHandler).Methods("DELETE")
router.Use(middleware.Logger)
router.Use(middleware.AllowContentEncoding("application/json"))
router.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler)
spa := server.NewSpaHandler("ui/dist/spa", "index.html")
router.PathPrefix("/").Handler(spa)
allowedHeaders := handlers.AllowedHeaders([]string{"X-Requested-With", "content-type"})
allowedOrigins := handlers.AllowedOrigins([]string{"*"})
allowedMethods := handlers.AllowedMethods([]string{"GET", "POST", "DELETE", "OPTIONS"})
log.Printf("Listening on %v:%v", address, port)
srv := &http.Server{
Handler: handlers.CORS(allowedOrigins, allowedHeaders, allowedMethods)(router),
Addr: address + ":" + port,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
srv.ListenAndServe()
}