forked from gaodoo/golang-restful-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
84 lines (68 loc) · 2.15 KB
/
server.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
package main
import (
"fmt"
"net/http"
"github.com/Sirupsen/logrus"
"github.com/go-ozzo/ozzo-dbx"
"github.com/go-ozzo/ozzo-routing"
"github.com/go-ozzo/ozzo-routing/auth"
"github.com/go-ozzo/ozzo-routing/content"
"github.com/go-ozzo/ozzo-routing/cors"
_ "github.com/lib/pq"
"github.com/qiangxue/golang-restful-starter-kit/apis"
"github.com/qiangxue/golang-restful-starter-kit/app"
"github.com/qiangxue/golang-restful-starter-kit/daos"
"github.com/qiangxue/golang-restful-starter-kit/errors"
"github.com/qiangxue/golang-restful-starter-kit/services"
)
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 := errors.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
// wire up API routing
http.Handle("/", buildRouter(logger, db))
// start the server
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() // skip all other middlewares/handlers
return c.Write("OK " + app.Version)
})
router.Use(
app.Init(logger),
content.TypeNegotiator(content.JSON),
cors.Handler(cors.Options{
AllowOrigins: "*",
AllowHeaders: "*",
AllowMethods: "*",
}),
app.Transactional(db),
)
rg := router.Group("/v1")
rg.Post("/auth", apis.Auth(app.Config.JWTSigningKey))
rg.Use(auth.JWT(app.Config.JWTVerificationKey, auth.JWTOptions{
SigningMethod: app.Config.JWTSigningMethod,
TokenHandler: apis.JWTHandler,
}))
artistDAO := daos.NewArtistDAO()
apis.ServeArtistResource(rg, services.NewArtistService(artistDAO))
// wire up more resource APIs here
return router
}