This repository has been archived by the owner on Sep 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
revel.go
289 lines (248 loc) · 9.01 KB
/
revel.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package revel
import (
"flag"
"go/build"
"log"
"os"
"path/filepath"
"strings"
"github.com/robfig/config"
"github.com/robfig/humanize"
"github.com/BSP-Mosaic/teltech-glog"
)
const (
REVEL_IMPORT_PATH = "github.com/BSP-Mosaic/teltech-revel"
)
var (
// App details
AppName string // e.g. "sample"
BasePath string // e.g. "/Users/robfig/gocode/src/corp/sample"
AppPath string // e.g. "/Users/robfig/gocode/src/corp/sample/app"
ViewsPath string // e.g. "/Users/robfig/gocode/src/corp/sample/app/views"
ImportPath string // e.g. "corp/sample"
SourcePath string // e.g. "/Users/robfig/gocode/src"
Config *MergedConfig
RunMode string // Application-defined (by default, "dev" or "prod")
DevMode bool // if true, RunMode is a development mode.
// Revel installation details
RevelPath string // e.g. "/Users/robfig/gocode/src/revel"
// Where to look for templates and configuration.
// Ordered by priority. (Earlier paths take precedence over later paths.)
CodePaths []string
ConfPaths []string
TemplatePaths []string
Modules []Module
// Server config.
//
// Alert: This is how the app is configured, which may be different from
// the current process reality. For example, if the app is configured for
// port 9000, HttpPort will always be 9000, even though in dev mode it is
// run on a random port and proxied.
HttpPort int // e.g. 9000
HttpAddr string // e.g. "", "127.0.0.1"
HttpSsl bool // e.g. true if using ssl
HttpSslCert string // e.g. "/path/to/cert.pem"
HttpSslKey string // e.g. "/path/to/key.pem"
CookiePrefix string // All cookies dropped by the framework begin with this prefix.
LogToStderr bool // If true, hard code logging configuration to logtostderr
// Cookie flags
CookieHttpOnly bool
CookieSecure bool
Initialized bool
// Private
secretKey []byte // Key used to sign cookies. An empty key disables signing.
packaged bool // If true, this is running from a pre-built package.
)
// Init initializes Revel -- it provides paths for getting around the app.
//
// Params:
// mode - the run mode, which determines which app.conf settings are used.
// importPath - the Go import path of the application.
// srcPath - the path to the source directory, containing Revel and the app.
// If not specified (""), then a functioning Go installation is required.
func Init(mode, importPath, srcPath string) {
// Ignore trailing slashes.
ImportPath = strings.TrimRight(importPath, "/")
SourcePath = srcPath
RunMode = mode
// If the SourcePath is not specified, find it using build.Import.
var revelSourcePath string // may be different from the app source path
if SourcePath == "" {
revelSourcePath, SourcePath = findSrcPaths(importPath)
} else {
// If the SourcePath was specified, assume both Revel and the app are within it.
SourcePath = filepath.Clean(SourcePath)
revelSourcePath = SourcePath
packaged = true
}
RevelPath = filepath.Join(revelSourcePath, filepath.FromSlash(REVEL_IMPORT_PATH))
BasePath = filepath.Join(SourcePath, filepath.FromSlash(importPath))
AppPath = filepath.Join(BasePath, "app")
ViewsPath = filepath.Join(AppPath, "views")
CodePaths = []string{AppPath}
ConfPaths = []string{
filepath.Join(BasePath, "conf"),
filepath.Join(RevelPath, "conf"),
}
TemplatePaths = []string{
ViewsPath,
filepath.Join(RevelPath, "templates"),
}
// Load app.conf
var err error
Config, err = LoadConfig("app.conf")
if err != nil || Config == nil {
glog.Fatalln("Failed to load app.conf:", err)
}
// Ensure that the selected runmode appears in app.conf.
// If empty string is passed as the mode, treat it as "DEFAULT"
if mode == "" {
mode = config.DEFAULT_SECTION
}
if !Config.HasSection(mode) {
glog.Fatalln("app.conf: No mode found:", mode)
}
Config.SetSection(mode)
// Configure properties from app.conf
DevMode = Config.BoolDefault("mode.dev", false)
HttpPort = Config.IntDefault("http.port", 9000)
HttpAddr = Config.StringDefault("http.addr", "")
HttpSsl = Config.BoolDefault("http.ssl", false)
HttpSslCert = Config.StringDefault("http.sslcert", "")
HttpSslKey = Config.StringDefault("http.sslkey", "")
if HttpSsl {
if HttpSslCert == "" {
log.Fatalln("No http.sslcert provided.")
}
if HttpSslKey == "" {
log.Fatalln("No http.sslkey provided.")
}
}
AppName = Config.StringDefault("app.name", "(not set)")
CookiePrefix = Config.StringDefault("cookie.prefix", "REVEL")
CookieHttpOnly = Config.BoolDefault("cookie.httponly", false)
CookieSecure = Config.BoolDefault("cookie.secure", false)
if secretStr := Config.StringDefault("app.secret", ""); secretStr != "" {
secretKey = []byte(secretStr)
}
Initialized = true
}
// ConfigureLogging applies the configuration in revel.Config to the glog flags.
// Logger flags specified explicitly on the command line are not changed.
func ConfigureLogging() {
// Get the flags specified on the command line.
specifiedFlags := make(map[string]struct{})
flag.Visit(func(f *flag.Flag) { specifiedFlags[f.Name] = struct{}{} })
// For each logger option in app.conf..
var err error
for _, option := range Config.Options("log.") {
val, _ := Config.String(option)
switch flagname := option[len("log."):]; flagname {
case "v", "vmodule", "logtostderr", "alsologtostderr", "stderrthreshold", "log_dir":
// If it was specified on the command line, don't set it from app.conf
if _, ok := specifiedFlags[flagname]; ok {
continue
}
// Look up the flag and set it.
// If it's log_dir, make it into an absolute path and creat it if necessary.
if flagname == "log_dir" {
if val, err = filepath.Abs(val); err != nil {
glog.Fatalln("Failed to get absolute path to log_dir:", err)
}
os.MkdirAll(val, 0777) // Create the log dir if it doesn't already exist.
}
if err = flag.Set(flagname, val); err != nil {
glog.Fatalf("Failed to set glog option for %s=%s: %s", flagname, val, err)
}
case "maxsize":
if glog.MaxSize, err = humanize.ParseBytes(val); err != nil {
glog.Fatalf("Failed to parse log.MaxSize=%s: %s", val, err)
}
}
}
}
// findSrcPaths uses the "go/build" package to find the source root for Revel
// and the app.
func findSrcPaths(importPath string) (revelSourcePath, appSourcePath string) {
var (
gopaths = filepath.SplitList(build.Default.GOPATH)
goroot = build.Default.GOROOT
)
if len(gopaths) == 0 {
glog.Fatal("GOPATH environment variable is not set. ",
"Please refer to http://golang.org/doc/code.html to configure your Go environment.")
}
if ContainsString(gopaths, goroot) {
glog.Fatalf("GOPATH (%s) must not include your GOROOT (%s). "+
"Please refer to http://golang.org/doc/code.html to configure your Go environment.",
gopaths, goroot)
}
appPkg, err := build.Import(importPath, "", build.FindOnly)
if err != nil {
glog.Fatalln("Failed to import", importPath, "with error:", err)
}
revelPkg, err := build.Import(REVEL_IMPORT_PATH, "", build.FindOnly)
if err != nil {
glog.Fatalln("Failed to find Revel with error:", err)
}
return revelPkg.SrcRoot, appPkg.SrcRoot
}
type Module struct {
Name, ImportPath, Path string
}
// LoadModules looks through Config for all modules that need to be loaded,
// adding their controllers and templates to the revel application.
func LoadModules() {
for _, key := range Config.Options("module.") {
moduleImportPath := Config.StringDefault(key, "")
if moduleImportPath == "" {
continue
}
modulePath, err := ResolveImportPath(moduleImportPath)
if err != nil {
glog.Fatalln("Failed to load module. Import of", moduleImportPath, "failed:", err)
}
addModule(key[len("module."):], moduleImportPath, modulePath)
}
}
// ResolveImportPath returns the filesystem path for the given import path.
// Returns an error if the import path could not be found.
func ResolveImportPath(importPath string) (string, error) {
if packaged {
return filepath.Join(SourcePath, filepath.FromSlash(importPath)), nil
}
modPkg, err := build.Import(importPath, "", build.FindOnly)
if err != nil {
return "", err
}
return modPkg.Dir, nil
}
func addModule(name, importPath, modulePath string) {
Modules = append(Modules, Module{Name: name, ImportPath: importPath, Path: modulePath})
if codePath := filepath.Join(modulePath, "app"); DirExists(codePath) {
CodePaths = append(CodePaths, codePath)
if viewsPath := filepath.Join(modulePath, "app", "views"); DirExists(viewsPath) {
TemplatePaths = append(TemplatePaths, viewsPath)
}
}
glog.Info("Loaded module ", filepath.Base(modulePath))
// Hack: There is presently no way for the testrunner module to add the
// "test" subdirectory to the CodePaths. So this does it instead.
if importPath == "github.com/BSP-Mosaic/teltech-revel/modules/testrunner" {
CodePaths = append(CodePaths, filepath.Join(BasePath, "tests"))
}
}
// ModuleByName returns the module of the given name, if loaded.
func ModuleByName(name string) (m Module, found bool) {
for _, module := range Modules {
if module.Name == name {
return module, true
}
}
return Module{}, false
}
func CheckInit() {
if !Initialized {
panic("Revel has not been initialized!")
}
}