/
polaris.go
202 lines (177 loc) · 5.59 KB
/
polaris.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Package polaris provides the major features to the end user. So far, it's a customized version of https://github.com/go-martini/martini/ with other packages.
// It proovides a solid project start in golang.
//
package polaris
import (
// "database/sql"
// _ "github.com/mattn/go-adodb"
"fmt"
"github.com/boj/redistore"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
"github.com/martini-contrib/sessionauth"
"github.com/martini-contrib/sessions"
// "github.com/robinmin/gorp"
log "github.com/robinmin/logo"
// stdlog "log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
// var (
// log_file string
// log_handle *os.File
// )
// PolarisApplication represents a Martini with some reasonable defaults same as the original ClassicMartini.
type PolarisApplication struct {
*martini.Martini
martini.Router
// Config is an user provided object to store relevant information
Config Config
// Store is a internal variable to store the RediStore object
Store *redistore.RediStore
// DbEngine is the pointer to a global query engine
DbEngine *DBEngine
}
// NewApp creates a application object with some basic default middleware. It's based on ClassicMartini.
// Classic also maps martini.Routes as a service.
func NewApp(cfg Config, newUser func() sessionauth.User) *PolarisApplication {
// Create config object
if !cfg.LoadConfig() {
log.Error("Failed to init config object")
return nil
}
config := cfg.GetBasicConfig()
log.Debug("Application started......")
// create router object
rtr := martini.NewRouter()
// create matini object
server := martini.New()
// replace log for testing
server.Map((*log.LevelBasedLogger)(nil))
server.Use(Logger())
server.Use(martini.Recovery())
server.Use(martini.Static(config.DirStatic))
server.MapTo(rtr, (*martini.Routes)(nil))
server.Action(rtr.Handle)
app := &PolarisApplication{server, rtr, cfg, nil, nil}
log.Debug("Add middleware -- martini-contrib/render......")
app.Use(render.Renderer(render.Options{
Directory: config.DirTemplate,
Extensions: []string{config.TempExtension},
Charset: config.TempEncoding,
}))
log.Debug("Add middleware -- martini-contrib/sessions......")
if "redis" == strings.ToLower(strings.TrimSpace(config.SessionStore)) {
var err error
log.Debug("Connect to redis......" + config.Redis.Address)
if app.Store == nil {
app.Store, err = redistore.NewRediStoreWithDB(
config.Redis.Size,
config.Redis.Network,
config.Redis.Address,
config.Redis.Password,
config.Redis.DB,
[]byte(config.SessionMask),
)
if err != nil {
log.Error("Failed to connect to redis : " + err.Error())
return nil
}
}
app.Use(sessions.Sessions(config.SessionName, app.Store))
} else {
app.Use(sessions.Sessions(config.SessionName, sessions.NewCookieStore([]byte(config.SessionMask))))
}
if len(config.Database.Database) > 0 {
log.Debug("Connect to databse......[" + config.Database.Database + "]")
// ensure the connection can be made corrrectly, connect to the dabase when starting
app.DbEngine = config.Database.InitDB()
if app.DbEngine == nil {
log.Error("Failed to connect to database (" + config.Database.Database + ")")
return nil
}
log.Debug("Add middleware -- gorp......")
app.Use(config.Database.MartiniHandler())
}
log.Debug("Add middleware -- martini-contrib/sessionauth......")
app.Use(sessionauth.SessionUser(newUser))
sessionauth.RedirectUrl = config.url["RedirectUrl"]
sessionauth.RedirectParam = config.url["RedirectParam"]
log.Debug("Add User defined router mapping......")
if !cfg.RoterMap(app) {
log.Error("Failed to add Roter Mapping")
return nil
}
return app
}
func (app *PolarisApplication) Close() bool {
log.Debug("Uninitializing application......")
config := app.Config.GetBasicConfig()
// close the redis session handle
if app.Store != nil {
app.Store.Close()
app.Store = nil
}
// close the handle of log file
if config.LogHandle != nil {
config.LogHandle.Close()
config.LogHandle = nil
}
if app.DbEngine != nil {
app.DbEngine.Close()
}
return true
}
func (app *PolarisApplication) RotateLog() bool {
config := app.Config.GetBasicConfig()
// get new log
year, month, day := time.Now().Date()
new_log := config.DirLog + "/" + fmt.Sprintf("app_%04d%02d%02d.log", year, month, day)
new_handle, err := os.OpenFile(new_log, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Error("error opening file: %v", err)
return false
}
// replace it
if config.LogHandle != nil {
config.LogHandle.Close()
}
config.LogHandle = new_handle
config.LogFile = new_log
return true
}
func (app *PolarisApplication) RunApp() bool {
config := app.Config.GetBasicConfig()
host := os.Getenv("HOST")
// if len(host) <= 0 {
// host = os.Getenv("COMPUTERNAME")
// }
port := config.Port
log.Info("listening on " + host + ":" + strconv.Itoa(port))
lgr := log.GetLogger("stdout")
if lgr != nil {
lgr.Fatalln(http.ListenAndServe(host+":"+strconv.Itoa(port), app))
return true
}
return false
}
// Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
func Logger() martini.Handler {
return func(res http.ResponseWriter, req *http.Request, c martini.Context, lgr *log.LevelBasedLogger) {
start := time.Now()
addr := req.Header.Get("X-Real-IP")
if addr == "" {
addr = req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = req.RemoteAddr
}
}
log.Debug("==>Started %s %s for %s", req.Method, req.URL.Path, addr)
rw := res.(martini.ResponseWriter)
c.Next()
log.Debug("<==Completed %v %s in %v\n", rw.Status(), http.StatusText(rw.Status()), time.Since(start))
}
}