-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
116 lines (94 loc) · 2.38 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
package main
import (
"bandersnatch/api/handlers"
"bandersnatch/pkg/entities"
"bandersnatch/pkg/game"
"bandersnatch/pkg/player"
"bandersnatch/utils"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/joho/godotenv"
"github.com/julienschmidt/httprouter"
"github.com/lib/pq"
negronilogrus "github.com/meatballhat/negroni-logrus"
"github.com/rs/cors"
log "github.com/sirupsen/logrus"
"github.com/urfave/negroni"
"net/http"
"os"
)
func init() {
log.SetFormatter(&log.JSONFormatter{PrettyPrint: true})
log.SetOutput(os.Stdout)
log.Printf("Running on %s", os.Getenv("ENV"))
if os.Getenv("ENV") != "PROD" {
err := godotenv.Load()
if err != nil {
log.Fatal(err)
}
}
}
func connectToDb() *gorm.DB {
conn, err := pq.ParseURL(os.Getenv("DB_URI"))
if err != nil {
log.Fatal(err)
return nil
}
db, err := gorm.Open("postgres", conn)
if err != nil {
log.Fatal(err)
return nil
}
if os.Getenv("DEBUG") == "true" {
db = db.Debug()
}
db.AutoMigrate(&entities.Player{})
return db
}
func initNegroni() *negroni.Negroni {
n := negroni.New()
n.Use(negronilogrus.NewCustomMiddleware(log.DebugLevel, &log.JSONFormatter{PrettyPrint: true}, "API requests"))
n.Use(negroni.NewRecovery())
return n
}
func main() {
utils.PrintAsciiArt()
nexus := &game.Nexus{}
if err := nexus.LoadFromFile(os.Getenv("NEXUS_FILE")); err != nil {
log.Fatal(err)
return
}
if err := nexus.LoadHintsFromFile(os.Getenv("HINTS_FILE")); err != nil {
log.Fatal(err)
return
}
n := initNegroni()
r := httprouter.New()
n.UseHandler(r)
db := connectToDb()
playerRepo := player.NewPostgresRepo(db)
playerSvc := player.NewService(playerRepo)
gameSvc := game.NewService(nexus)
handlers.MakePlayerHandlers(r, playerSvc)
handlers.MakeGameHandlers(r, playerSvc, gameSvc)
port := os.Getenv("PORT")
if port == "" {
port = "1729"
}
r.HandlerFunc("POST", "/api/bandersnatch/health", func(w http.ResponseWriter, r *http.Request) {
utils.RespWrap(w, http.StatusOK, "Good")
})
log.WithField("event", "START").Info("Listening on port " + port)
c := cors.New(cors.Options{
AllowedHeaders: []string{"Authorization", "Content-Type"},
AllowedOrigins: []string{"*"},
AllowedMethods: []string{http.MethodGet, http.MethodPost},
})
handler := c.Handler(r)
err := http.ListenAndServe(fmt.Sprintf(":%s", port), handler)
if err != nil {
log.Fatal(err)
return
}
}