DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 5d0b5199c38d0807b8ff9cadde4ea27f86ab541e deck-builder/.archived/sdbapi/main.go -rw-r--r-- 1.9 KiB
5d0b5199Jonni Liljamo feat(api): session validation 1 year, 9 months ago
                                                                                
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
/*
 * This file is part of sdbapi
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

package main

import (
	"api/db"
	"api/handlers"
	"api/middlewares"
	"log"
	_ "net/http/pprof"
	"os"
	"syscall"

	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
)

func main() {
	// stores various errors during startup
	var err error

	err = setUlimits()
	if err != nil {
		log.Fatal("failed to set Ulimits")
	}

	dbConnectionString := os.Getenv("GORM_DB_STRING")
	if dbConnectionString == "" {
		log.Fatal("environment variable 'GORM_DB_STRING' is not set")
	}

	err = db.Connect(dbConnectionString)
	if err != nil {
		log.Fatal(err)
	}

	db.Migrate()

	log.Print("creating router and launching API")
	router := createRouter()
	router.Run(":3000")
}

func createRouter() *gin.Engine {
	router := gin.Default()
	pprof.Register(router)
	api := router.Group("/api")
	{
		api.GET("/info", handlers.Info)
		api.GET("/ws", handlers.WS)
		user := api.Group("/user")
		{
			user.POST("/register", handlers.CreateUser)
			user.POST("/token", handlers.GenerateToken)
			user.GET("/:id", handlers.UserInfo)
			userp := user.Group("/_").Use(middlewares.Auth())
			{
				userp.GET("/:id", handlers.UserInfoP)
			}
		}
		game := api.Group("/game").Use(middlewares.Auth())
		{
			game.GET("/:id", handlers.GameInfo)
			game.GET("/all_forming", handlers.FormingGames)
			game.POST("/create", handlers.CreateGame)
			game.PATCH("/:id/state", handlers.PatchGameState)
			game.GET("/my_games", handlers.MyGames)
			game.POST("/:id/join", handlers.JoinGame)
		}
	}
	return router
}

// Set NOFILE limit to max, to allow more concurrent websocket connections
func setUlimits() error {
	var rlimit syscall.Rlimit
	if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {
		return err
	}
	rlimit.Cur = rlimit.Max
	return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit)
}