-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.go
More file actions
90 lines (73 loc) · 2.29 KB
/
server.go
File metadata and controls
90 lines (73 loc) · 2.29 KB
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
package main
import (
"fmt"
"net/http"
"io/ioutil"
"gopkg.in/yaml.v2"
"github.com/Sirupsen/logrus"
"github.com/go-ozzo/ozzo-dbx"
"github.com/go-ozzo/ozzo-routing"
"github.com/go-ozzo/ozzo-routing/content"
"github.com/go-ozzo/ozzo-routing/cors"
_ "github.com/lib/pq"
"github.com/DecenterApps/CryptageCodeRedeem/endpoint"
"github.com/DecenterApps/CryptageCodeRedeem/app"
"github.com/DecenterApps/CryptageCodeRedeem/dao"
"github.com/DecenterApps/CryptageCodeRedeem/service"
cryptageError "github.com/DecenterApps/CryptageCodeRedeem/error"
)
func main() {
// load application configurations
if err := app.LoadConfig("./config"); err != nil {
panic(fmt.Errorf("Invalid application configuration: %s", err))
}
// load error messages
if err := cryptageError.LoadMessages(app.Config.ErrorFile); err != nil {
panic(fmt.Errorf("Failed to read the error message file: %s", err))
}
// create the logger
logger := logrus.New()
// connect to the database
db, err := dbx.MustOpen("postgres", app.Config.DSN)
if err != nil {
panic(err)
}
db.LogFunc = logger.Infof
http.Handle("/", buildRouter(logger, db))
address := fmt.Sprintf(":%v", app.Config.ServerPort)
logger.Infof("server %v is started at %v\n", app.Version, address)
panic(http.ListenAndServe(address, nil))
}
func buildRouter(logger *logrus.Logger, db *dbx.DB) *routing.Router {
router := routing.New()
router.To("GET,HEAD", "/ping", func(c *routing.Context) error {
c.Abort()
return c.Write("OK " + app.Version)
})
router.Use(
app.Init(logger),
content.TypeNegotiator("text/html"),
cors.Handler(cors.Options{
AllowOrigins: "*",
AllowHeaders: "*",
AllowMethods: "*",
}),
app.Transactional(db),
)
rg := router.Group("")
endpoint.ServeCouponResource(rg, service.NewCouponService(dao.NewCouponDAO()), service.NewCardService(dao.NewCardDAO(getCryptageCards())))
return router
}
func getCryptageCards() app.Cryptage {
var cryptage app.Cryptage
cardsYaml, _ := ioutil.ReadFile(app.Config.Cards)
yaml.Unmarshal(cardsYaml, &cryptage)
for i := 0; i < len(cryptage.Cards); i++ {
for j := 1; j <= len(cryptage.Cards[uint(i)]); j++ {
card := cryptage.Cards[uint(i)][uint(j)]
cryptage.Cards[uint(i)][card.Level] = card
}
delete(cryptage.Cards[uint(i)], uint(len(cryptage.Cards[uint(i)])-1))
}
return cryptage
}