/
web-server.go
53 lines (40 loc) · 1.27 KB
/
web-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
package web
import (
"github.com/Sfeir/golang-200/dao"
"github.com/meatballhat/negroni-logrus"
"github.com/rs/cors"
logger "github.com/sirupsen/logrus"
"github.com/urfave/negroni"
"time"
)
// BuildWebServer constructs a new web server with the right DAO and tasks handler
func BuildWebServer(db, migration string, daoType dao.DBType, statisticsDuration time.Duration) (*negroni.Negroni, error) {
// task dao
td, err := dao.GetTaskDAO(db, migration, daoType)
if err != nil {
logger.WithField("error", err).WithField("dbtype", daoType).WithField("params", db).
Warn("unable to build the required DAO")
return nil, err
}
// web server
n := negroni.New()
// add middleware for logging
n.Use(negronilogrus.NewMiddlewareFromLogger(logger.StandardLogger(), "task"))
// add recovery middleware in case of panic in handler func
recovery := negroni.NewRecovery()
recovery.PrintStack = false
n.Use(recovery)
// add statistics middleware
n.Use(NewStatisticsMiddleware(statisticsDuration))
// add CORS (all origins, all methods)
n.Use(cors.AllowAll())
// add as many middleware as you like
// ...
// new controller
controller := NewTaskController(td)
// new router
router := NewRouter(controller)
// route handler goes last
n.UseHandler(router)
return n, nil
}