/
common.go
350 lines (302 loc) · 9.34 KB
/
common.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Copyright (c) 2016 OpenM++
// This code is licensed under the MIT license (see LICENSE.txt for details)
package main
import (
"errors"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/husobee/vestigo"
"golang.org/x/text/language"
"github.com/openmpp/go/ompp/helper"
"github.com/openmpp/go/ompp/omppLog"
)
// logRequest is a middelware to log http request
func logRequest(next http.HandlerFunc) http.HandlerFunc {
if isLogRequest {
return func(w http.ResponseWriter, r *http.Request) {
omppLog.Log(r.Method, ": ", r.Host, r.URL)
next(w, r)
}
} // else
return next
}
// match request language with UI supported languages and return canonic language name
func matchRequestToUiLang(r *http.Request) string {
rqLangTags, _, _ := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
tag, _, _ := uiLangMatcher.Match(rqLangTags...)
return tag.String()
}
// get value of url parameter ?name or router parameter /:name
func getRequestParam(r *http.Request, name string) string {
v := r.URL.Query().Get(name)
if v == "" {
v = vestigo.Param(r, name)
}
return v
}
// get boolean value of url parameter ?name or router parameter /:name
func getBoolRequestParam(r *http.Request, name string) (bool, bool) {
v := r.URL.Query().Get(name)
if v == "" {
v = vestigo.Param(r, name)
}
if v == "" {
return false, true // no such parameter: return = false by default
}
if isVal, err := strconv.ParseBool(v); err == nil {
return isVal, true // return result: value is boolean
}
return false, false // value is not boolean
}
// get integer value of url parameter ?name or router parameter /:name
func getIntRequestParam(r *http.Request, name string, defaultVal int) (int, bool) {
v := r.URL.Query().Get(name)
if v == "" {
v = vestigo.Param(r, name)
}
if v == "" {
return defaultVal, true // no such parameter: return defult value
}
if nVal, err := strconv.Atoi(v); err == nil {
return nVal, true // return result: value is integer
}
return defaultVal, false // value is not integer
}
// get int64 value of url parameter ?name or router parameter /:name
func getInt64RequestParam(r *http.Request, name string, defaultVal int64) (int64, bool) {
v := r.URL.Query().Get(name)
if v == "" {
v = vestigo.Param(r, name)
}
if v == "" {
return defaultVal, true // no such parameter: return defult value
}
if nVal, err := strconv.ParseInt(v, 0, 64); err == nil {
return nVal, true // return result: value is integer
}
return defaultVal, false // value is not integer
}
// get languages accepted by browser and by optional language request parameter, for example: ..../lang:EN
// if language parameter specified then return it as a first element of result (it a preferred language)
func getRequestLang(r *http.Request, name string) []language.Tag {
// browser languages
rqLangTags, _, _ := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
// if optional url parameter ?lang or router parameter /:lang specified
ln := r.URL.Query().Get(name)
if ln == "" {
ln = vestigo.Param(r, name)
}
// add lang parameter as top language
if ln != "" {
if t := language.Make(ln); t != language.Und {
rqLangTags = append([]language.Tag{t}, rqLangTags...)
}
}
return rqLangTags
}
// set Content-Type header by extension and invoke next handler.
// This function exist to suppress Windows registry content type overrides
func setContentType(next http.Handler) http.Handler {
var ctDef = map[string]string{
".css": "text/css; charset=utf-8",
".js": "text/javascript",
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ext := filepath.Ext(r.URL.Path); ext != "" {
if ct := ctDef[strings.ToLower(ext)]; ct != "" {
w.Header().Set("Content-Type", ct)
}
}
next.ServeHTTP(w, r) // invoke next handler
})
}
// set csv response headers: Content-Type: application/csv, Content-Disposition and Cache-Control
func csvSetHeaders(w http.ResponseWriter, name string) {
// set response headers: no Content-Length result in Transfer-Encoding: chunked
// todo: ETag instead no-cache and utf-8 file names
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Header().Set("Content-Disposition", "attachment; filename="+`"`+url.QueryEscape(name)+".csv"+`"`)
w.Header().Set("Cache-Control", "no-cache")
}
// dirExist return error if directory does not exist or not accessible
func dirExist(dirPath string) bool {
if dirPath == "" {
return false
}
_, err := dirStat(dirPath)
return err == nil
}
// return file Stat if this is a directory
func dirStat(dirPath string) (fs.FileInfo, error) {
fi, err := os.Stat(dirPath)
if err != nil {
if os.IsNotExist(err) {
return fi, errors.New("Error: directory not exist: " + dirPath)
}
return fi, errors.New("Error: unable to access directory: " + dirPath + " : " + err.Error())
}
if !fi.IsDir() {
return fi, errors.New("Error: directory expected: " + dirPath)
}
return fi, nil
}
// fileExist return error if file not exist, not accessible or it is not a regular file
func fileExist(filePath string) bool {
if filePath == "" {
return false
}
_, err := fileStat(filePath)
return err == nil
}
// return file Stat if this is a regular file
func fileStat(filePath string) (fs.FileInfo, error) {
fi, err := os.Stat(filePath)
if err != nil {
if os.IsNotExist(err) {
return fi, errors.New("Error: file not exist: " + filePath)
}
return fi, errors.New("Error: unable to access file: " + filePath + " : " + err.Error())
}
if fi.IsDir() || !fi.Mode().IsRegular() {
return fi, errors.New("Error: it is not a regilar file: " + filePath)
}
return fi, nil
}
// return list of files by pattern, on error log error message
func filesByPattern(ptrn string, msg string) []string {
fLst, err := filepath.Glob(ptrn)
if err != nil {
omppLog.Log(msg, ": ", ptrn)
return []string{}
}
return fLst
}
// Delete file and log path if isLog is true, return false on delete error.
func fileDeleteAndLog(isLog bool, path string) bool {
if isLog {
omppLog.Log("Delete: ", path)
}
if e := os.Remove(path); e != nil && !os.IsNotExist(e) {
omppLog.Log(e)
return false
}
return true
}
// Move file to new location and log it if isLog is true, return false on move error.
func fileMoveAndLog(isLog bool, srcPath string, dstPath string) bool {
if srcPath == "" || dstPath == "" {
return false
}
if isLog {
omppLog.Log("Move: ", srcPath, " To: ", dstPath)
}
if e := os.Rename(srcPath, dstPath); e != nil && !os.IsNotExist(e) {
omppLog.Log(e)
return false
}
return true
}
// Create or truncate existing file and log path if isLog is true, return false on create error.
func fileCreateEmpty(isLog bool, fPath string) bool {
if isLog {
omppLog.Log("Create: ", fPath)
}
f, err := os.OpenFile(fPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
omppLog.Log(err)
return false
}
defer f.Close()
return true
}
// Copy file and log path if isLog is true, return false on error of if source file not exists
func fileCopy(isLog bool, src, dst string) bool {
if src == "" || dst == "" || src == dst {
return false
}
if isLog {
omppLog.Log("Copy: ", src, " -> ", dst)
}
inp, err := os.Open(src)
if err != nil {
if os.IsNotExist(err) {
if isLog {
omppLog.Log("File not found: ", src)
}
} else {
omppLog.Log(err)
}
return false
}
defer inp.Close()
out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
omppLog.Log(err)
return false
}
defer out.Close()
if _, err = io.Copy(out, inp); err != nil {
omppLog.Log(err)
return false
}
return true
}
// append to message to log file
func writeToCmdLog(logPath string, isDoTimestamp bool, msg ...string) bool {
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return false // disable log on error
}
defer f.Close()
tsPrefix := helper.MakeDateTime(time.Now()) + " "
for _, m := range msg {
if isDoTimestamp {
if _, err = f.WriteString(tsPrefix); err != nil {
return false // disable log on error
}
}
if _, err = f.WriteString(m); err != nil {
return false // disable log on error
}
if runtime.GOOS == "windows" { // adjust newline for windows
_, err = f.WriteString("\r\n")
} else {
_, err = f.WriteString("\n")
}
if err != nil {
return false
}
}
return err == nil // disable log on error
}
// dbcopyPath return path to dbcopy.exe, it is expected to be in the same directory as oms.exe.
// argument omsAbsPath expected to be /absolute/path/to/oms.exe
func dbcopyPath(omsAbsPath string) string {
d := filepath.Dir(omsAbsPath)
p := filepath.Join(d, "dbcopy.exe")
if fileExist(p) {
return p
}
p = filepath.Join(d, "dbcopy")
if fileExist(p) {
return p
}
return "" // dbcopy not found or not accessible or it is not a regular file
}
// wait for doneC exit signal or sleep, return true on exit signal or return false at the end of sleep interval
func isExitSleep(ms time.Duration, doneC <-chan bool) bool {
select {
case <-doneC:
return true
case <-time.After(ms * time.Millisecond):
}
return false
}