-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
243 lines (190 loc) · 6.82 KB
/
app.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
package goappbase
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"runtime"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/mitoteam/mttools"
"github.com/spf13/cobra"
)
const DEV_MODE_LABEL = "DEV"
// Variables to be set by compiler
var (
BuildVersion = DEV_MODE_LABEL
BuildCommit = DEV_MODE_LABEL
BuildTime = DEV_MODE_LABEL
)
type AppBase struct {
ExecutableName string //executable command name
AppName string //Long name
LongDescription string //Long description
Version string //Version (auto set by compiler)
BuildCommitFull string //Git full commit hash
BuildCommit string //Git short commit hash
BuildTime string //Build time
BuildWith string //Build information
Global map[string]interface{} //some global application state values
AppSettingsFilename string // with .yml extension please
AppSettings interface{} //pointer to struct embedding AppSettingsBase
baseSettings *AppSettingsBase //pointer to *AppSettingsBase, set in internalInit()
serviceAutostart bool
rootCmd *cobra.Command
//contexts and timeout settings
BaseContext context.Context
ShutdownTimeout time.Duration
//web router
webRouter *gin.Engine
WebRouterLogQueries bool // true = extended query logging (--query-log option of `run`)
BuildWebRouterF func(r *gin.Engine) // function to build web router for `run` command
//web api
WebApiPathPrefix string // usually "/api". Leave empty to disable web API at all.
WebApiEnableGet bool // Serve both POST and GET methods. Default 'false' = POST-requests only.
webApiHandlerList map[string]ApiRequestHandler
//callbacks (aka event handlers)
PreCmdF func(cmd *cobra.Command) error // called before any subcommand. Stops executions if error returned.
PostCmdF func(cmd *cobra.Command) error // called after any subcommand. Stops executions if error returned.
PreRunF func() error // called before starting `run` command. Stops executions if error returned.
PostRunF func() error // called after finishing `run` command. Stops executions if error returned.
InitF func() error // Additional code for `init` subcommand. Stops executions if error returned.
PrintInfoF func() // Prints additional information when `info` subcommand called.
BuildCustomCommandsF func(rootCmd *cobra.Command) // Set this to add any custom subcommands
}
// Initializes new application.
// settings - application settings default values. Pointer to struct that embeds AppSettingsBase.
func NewAppBase(settings interface{}) *AppBase {
app := AppBase{}
//global app state values
app.Global = make(map[string]interface{})
//web api routes list
app.webApiHandlerList = make(map[string]ApiRequestHandler)
//default settings values
app.AppSettingsFilename = ".settings.yml"
if settings == nil {
log.Fatalln("settings should not be empty")
}
base_settings_type := reflect.TypeOf((*AppSettingsBase)(nil)).Elem()
if !mttools.IsStructEmbeds(settings, base_settings_type) {
log.Fatalln("settings structure should embed " + base_settings_type.Name())
}
app.AppSettings = settings
v := reflect.ValueOf(app.AppSettings).Elem()
app.baseSettings = v.FieldByName(base_settings_type.Name()).Addr().Interface().(*AppSettingsBase)
app.baseSettings.checkDefaultValues(&AppSettingsBase{
WebserverHostname: "localhost",
WebserverPort: 15115,
ServiceName: app.ExecutableName,
ServiceUser: "www-data",
ServiceGroup: "www-data",
InitialRootPassword: mttools.RandomString(20),
})
//global application base context
app.BaseContext = context.Background()
//compilation data
app.Version = BuildVersion
app.BuildCommitFull = BuildCommit
app.BuildCommit = app.BuildCommitFull[0:min(7, len(app.BuildCommitFull))]
app.BuildTime = BuildTime
app.BuildWith = runtime.Version()
//set default values
app.ExecutableName = "UNSET_ExecutableName"
app.AppName = "UNSET_AppName"
app.ShutdownTimeout = 10 * time.Second
//build root cobra cmd
app.buildRootCmd()
return &app
}
func (app *AppBase) Run() {
app.internalInit()
//cli application - we just let cobra to do its job
if err := app.rootCmd.Execute(); err != nil {
log.Fatalln(err)
}
}
func (app *AppBase) internalInit() {
//post-setup root cmd
app.rootCmd.Use = app.ExecutableName
app.rootCmd.Long = app.AppName
if app.LongDescription != "" {
app.rootCmd.Long += " - " + app.LongDescription
}
app.rootCmd.PersistentFlags().StringVar(
&app.AppSettingsFilename,
"settings",
app.AppSettingsFilename,
"Filename or full path bot settings file.",
)
//check app options
if app.WebApiPathPrefix != "" {
// no trailing slashes
app.WebApiPathPrefix = strings.TrimSuffix(app.WebApiPathPrefix, "/")
//should start from slash
if !strings.HasPrefix(app.WebApiPathPrefix, "/") {
app.WebApiPathPrefix += "/"
}
}
//add built-in commands
app.rootCmd.AddCommand(
app.buildVersionCmd(),
app.buildInstallCmd(),
app.buildUninstallCmd(),
app.buildInitCmd(),
app.buildInfoCmd(),
app.buildRunCmd(),
)
if app.BuildCustomCommandsF != nil {
app.BuildCustomCommandsF(app.rootCmd)
}
}
func (app *AppBase) loadSettings() error {
if mttools.IsFileExists(app.AppSettingsFilename) {
if err := mttools.LoadYamlSettingFromFile(app.AppSettingsFilename, app.AppSettings); err != nil {
return err
}
} else {
return fmt.Errorf("File not found: %s", app.AppSettingsFilename)
}
// Settings post-processing
if app.baseSettings.Production {
// require some settings in PRODUCTION
if app.baseSettings.BaseUrl == "" {
return errors.New("base_url required in production")
}
if app.baseSettings.WebserverCookieSecret == "" {
return errors.New("webserver_cookie_secret required in production")
} else if len(app.baseSettings.WebserverCookieSecret) < 32 {
return fmt.Errorf(
"webserver_cookie_secret should be at least 32 characters long in production. You have %d.",
len(app.baseSettings.WebserverCookieSecret),
)
}
} else {
// or use pre-defined values in DEV
if app.baseSettings.BaseUrl == "" {
app.baseSettings.BaseUrl = "http://" + app.baseSettings.WebserverHostname +
":" + strconv.Itoa(int(app.baseSettings.WebserverPort))
}
if app.baseSettings.WebserverCookieSecret == "" {
app.baseSettings.WebserverCookieSecret = "DEFAULT_DEV_SECRET"
}
}
return nil
}
func (app *AppBase) saveSettings(comment string) error {
return mttools.SaveYamlSettingToFile(app.AppSettingsFilename, comment, app.AppSettings)
}
func (app *AppBase) printSettings() {
mttools.PrintYamlSettings(app.AppSettings)
}
func (app *AppBase) ApiHandler(path string, handler ApiRequestHandler) *AppBase {
app.webApiHandlerList[path] = handler
return app //for method chaining
}
func (app *AppBase) IsDevMode() bool {
return app.Version == DEV_MODE_LABEL // && false //uncomment to debug production mode
}