-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathceleritas.go
363 lines (315 loc) · 8.14 KB
/
celeritas.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
351
352
353
354
355
356
357
358
359
360
361
362
363
package celeritas
import (
"fmt"
"github.com/CloudyKit/jet/v6"
"github.com/alexedwards/scs/v2"
"github.com/dgraph-io/badger/v3"
"github.com/go-chi/chi/v5"
"github.com/gomodule/redigo/redis"
"github.com/joho/godotenv"
"github.com/pnunn/celeritas/cache"
"github.com/pnunn/celeritas/mailer"
"github.com/pnunn/celeritas/render"
"github.com/pnunn/celeritas/session"
"github.com/robfig/cron/v3"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const version = "1.0.0"
var myRedisCache *cache.RedisCache
var myBadgerCache *cache.BadgerCache
var redisPool *redis.Pool
var badgerConn *badger.DB
type Celeritas struct {
AppName string
Debug bool
Version string
ErrorLog *log.Logger
InfoLog *log.Logger
RootPath string
Routes *chi.Mux
Render *render.Render
Session *scs.SessionManager
DB Database
JetViews *jet.Set
config config
EncryptionKey string
Cache cache.Cache
Scheduler *cron.Cron
Mail mailer.Mail
Server Server
}
type Server struct {
ServerName string
Port string
Secure bool
URL string
}
type config struct {
port string
renderer string
cookie cookieConfig
sessionType string
database databaseConfig
redis redisConfig
}
func (c *Celeritas) New(rootPath string) error {
pathConfig := initPaths{
rootPath: rootPath,
folderNames: []string{"handlers", "migrations", "views", "mail", "data", "public", "tmp", "logs", "middleware"},
}
err := c.Init(pathConfig)
if err != nil {
return err
}
err = c.checkDotEnv(rootPath)
if err != nil {
return err
}
// read .env
err = godotenv.Load(rootPath + "/.env")
if err != nil {
return err
}
// create loggers
infoLog, errorLog := c.startLoggers()
// connect to database
if os.Getenv("DATABASE_TYPE") != "" {
db, err := c.OpenDB(os.Getenv("DATABASE_TYPE"), c.BuildDNS())
if err != nil {
errorLog.Println(err)
os.Exit(1)
}
c.DB = Database{
DatabaseType: os.Getenv("DATABASE_TYPE"),
Pool: db,
}
}
if os.Getenv("CACHE") == "redis" || os.Getenv("SESSION_TYPE") == "redis" {
myRedisCache = c.createClientRedisCache()
c.Cache = myRedisCache
redisPool = myRedisCache.Conn
}
scheduler := cron.New()
c.Scheduler = scheduler
if os.Getenv("CACHE") == "badger" {
myBadgerCache = c.createClientBadgerCache()
c.Cache = myBadgerCache
badgerConn = myBadgerCache.Conn
_, err := c.Scheduler.AddFunc("@daily", func() {
_ = myBadgerCache.Conn.RunValueLogGC(0.7)
})
if err != nil {
return err
}
}
c.InfoLog = infoLog
c.ErrorLog = errorLog
c.Debug, _ = strconv.ParseBool(os.Getenv("DEBUG"))
c.Version = version
c.RootPath = rootPath
c.Routes = c.routes().(*chi.Mux)
c.Mail = c.createMailer()
c.config = config{
port: os.Getenv("PORT"),
renderer: os.Getenv("RENDERER"),
cookie: cookieConfig{
name: os.Getenv("COOKIE_NAME"),
lifetime: os.Getenv("COOKIE_LIFETIME"),
persist: os.Getenv("COOKIE_PERSIST"),
secure: os.Getenv("COOKIE_SECURE"),
domain: os.Getenv("COOKIE_DOMAIN"),
},
sessionType: os.Getenv("SESSION_TYPE"),
database: databaseConfig{
database: os.Getenv("DATABASE_TYPE"),
dsn: c.BuildDNS(),
},
redis: redisConfig{
host: os.Getenv("REDIS_HOST"),
password: os.Getenv("REDIS_PASSWORD"),
prefix: os.Getenv("REDIS_PREFIX"),
},
}
secure := true
if strings.ToLower(os.Getenv("SECURE")) == "false" {
secure = false
}
c.Server = Server{
ServerName: os.Getenv("SERVER_NAME"),
Port: os.Getenv("PORT"),
Secure: secure,
URL: os.Getenv("APP_URL"),
}
// create session
sess := session.Session{
CookieLifetime: c.config.cookie.lifetime,
CookiePersist: c.config.cookie.persist,
CookieName: c.config.cookie.name,
CookieDomain: c.config.cookie.domain,
SessionType: c.config.sessionType,
}
switch c.config.sessionType {
case "redis":
sess.RedisPool = myRedisCache.Conn
case "mysql", "postgres", "mariadb", "postgresql":
sess.DBPool = c.DB.Pool
}
c.Session = sess.InitSession()
c.EncryptionKey = os.Getenv("KEY")
if c.Debug {
var views = jet.NewSet(
jet.NewOSFileSystemLoader(fmt.Sprintf("%s/views", rootPath)),
jet.InDevelopmentMode(),
)
c.JetViews = views
} else {
var views = jet.NewSet(
jet.NewOSFileSystemLoader(fmt.Sprintf("%s/views", rootPath)),
)
c.JetViews = views
}
var views = jet.NewSet(
jet.NewOSFileSystemLoader(fmt.Sprintf("%s/views", rootPath)),
//jet.InDevelopmentMode(),
)
c.JetViews = views
c.createRenderer()
go c.Mail.ListenForMail()
return nil
}
func (c *Celeritas) Init(p initPaths) error {
root := p.rootPath
for _, path := range p.folderNames {
// create the folder if it doesn't exist
err := c.CreateDirIfNotExist(root + "/" + path)
if err != nil {
return err
}
}
return nil
}
// ListenAndServer starts the web server
func (c *Celeritas) ListenAndServer() {
srv := &http.Server{
Addr: fmt.Sprintf(":%s", os.Getenv("PORT")),
ErrorLog: c.ErrorLog,
Handler: c.Routes,
IdleTimeout: 30 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 600 * time.Second,
}
if c.DB.Pool != nil {
defer c.DB.Pool.Close()
}
if redisPool != nil {
defer redisPool.Close()
}
if badgerConn != nil {
defer badgerConn.Close()
}
c.InfoLog.Printf("Listening on port %s", os.Getenv("PORT"))
err := srv.ListenAndServe()
c.ErrorLog.Fatal(err)
}
func (c *Celeritas) checkDotEnv(path string) error {
err := c.CreateFileIfNotExist(fmt.Sprintf("%s/.env", path))
if err != nil {
return err
}
return nil
}
func (c *Celeritas) startLoggers() (*log.Logger, *log.Logger) {
var infoLog *log.Logger
var errorLog *log.Logger
infoLog = log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
errorLog = log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
return infoLog, errorLog
}
func (c *Celeritas) createRenderer() {
myRenderer := render.Render{
Renderer: c.config.renderer,
RootPath: c.RootPath,
Port: c.config.port,
JetViews: c.JetViews,
Session: c.Session,
}
c.Render = &myRenderer
}
func (c *Celeritas) createMailer() mailer.Mail {
port, _ := strconv.Atoi(os.Getenv("SMTP_PORT"))
m := mailer.Mail{
Domain: os.Getenv("MAIL_DOMAIN"),
Templates: c.RootPath + "/mail",
Host: os.Getenv("SMTP_HOST"),
Port: port,
Username: os.Getenv("SMTP_USERNAME"),
Password: os.Getenv("SMTP_PASSWORD"),
Encryption: os.Getenv("SMTP_ENCRYPTION"),
FromName: os.Getenv("FROM_NAME"),
FromAddress: os.Getenv("FROM_ADDRESS"),
Jobs: make(chan mailer.Message, 20),
Results: make(chan mailer.Result, 20),
API: os.Getenv("MAILER_API"),
APIKey: os.Getenv("MAILER_KEY"),
APIUrl: os.Getenv("MAILER_URL"),
}
return m
}
func (c *Celeritas) createClientRedisCache() *cache.RedisCache {
cacheClient := cache.RedisCache{
Conn: c.createRedisPool(),
Prefix: c.config.redis.prefix,
}
return &cacheClient
}
func (c *Celeritas) createClientBadgerCache() *cache.BadgerCache {
cacheClient := cache.BadgerCache{
Conn: c.createBadgerConn(),
}
return &cacheClient
}
func (c *Celeritas) createRedisPool() *redis.Pool {
return &redis.Pool{
MaxIdle: 50,
MaxActive: 10000,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp",
c.config.redis.host,
redis.DialPassword(c.config.redis.password))
},
TestOnBorrow: func(conn redis.Conn, t time.Time) error {
_, err := conn.Do("PING")
return err
},
}
}
func (c *Celeritas) createBadgerConn() *badger.DB {
db, err := badger.Open(badger.DefaultOptions(c.RootPath + "/tmp/badger"))
if err != nil {
return nil
}
return db
}
func (c *Celeritas) BuildDNS() string {
var dsn string
switch os.Getenv("DATABASE_TYPE") {
case "postgres", "postgresql":
dsn = fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=%s timezone=UTC connect_timeout=5",
os.Getenv("DATABASE_HOST"),
os.Getenv("DATABASE_PORT"),
os.Getenv("DATABASE_USER"),
os.Getenv("DATABASE_NAME"),
os.Getenv("DATABASE_SSL_MODE"))
if os.Getenv("DATABASE_PASS") != "" {
dsn = fmt.Sprintf("%s password=%s", dsn, os.Getenv("DATABASE_PASS"))
}
default:
}
return dsn
}