-
Notifications
You must be signed in to change notification settings - Fork 0
/
rasant.go
307 lines (259 loc) · 7.01 KB
/
rasant.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
package rasant
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"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/robfig/cron/v3"
"github.com/shaynemeyer/rasant/cache"
"github.com/shaynemeyer/rasant/render"
"github.com/shaynemeyer/rasant/session"
)
const version = "1.0.0"
var myRedisCache *cache.RedisCache
var myBadgerCache *cache.BadgerCache
// Rasant is the overall type for the Rasant package. Members that are exported in this type
// are available to any application that uses it.
type Rasant 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
}
type config struct {
port string
renderer string
cookie cookieConfig
sessionType string
database databaseConfig
redis redisConfig
}
// New reads the .env file, creates our application config, populates the Rasant type with settings
// based on .env values, and creates necessary folders and files if they don't exist
func (ras *Rasant) New(rootPath string) error {
pathConfig := initPaths{
rootPath: rootPath,
folderNames: []string{"handlers", "migrations", "views", "data", "public", "tmp", "logs", "middleware"},
}
err := ras.Init(pathConfig)
if err != nil {
return err
}
err = ras.checkDotEnv(rootPath)
if err != nil {
return err
}
// read .env
err = godotenv.Load(rootPath + "/.env")
if err != nil {
return err
}
// create loggers
infoLog, errorLog := ras.startLoggers()
// connect to database
if os.Getenv("DATABASE_TYPE") != "" {
db, err := ras.OpenDB(os.Getenv("DATABASE_TYPE"), ras.BuildDSN())
if err!= nil {
errorLog.Println(err)
os.Exit(1)
}
ras.DB = Database{
DataType: os.Getenv("DATABASE_TYPE"),
Pool: db,
}
}
if os.Getenv("CACHE") == "redis" || os.Getenv("SESSION_TYPE") == "redis" {
myRedisCache = ras.createClientRedisCache()
ras.Cache = myRedisCache
}
if os.Getenv("CACHE") == "badger" {
myBadgerCache = ras.createClientBadgerCache()
ras.Cache = myBadgerCache
_, err = ras.Scheduler.AddFunc("@daily", func() {
_ = myBadgerCache.Conn.RunValueLogGC(0.7)
})
if err != nil {
return err
}
}
ras.InfoLog = infoLog
ras.ErrorLog = errorLog
ras.Debug, _ = strconv.ParseBool(os.Getenv("DEBUG"))
ras.Version = version
ras.RootPath = rootPath
ras.Routes = ras.routes().(*chi.Mux)
ras.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_PERSISTS"),
secure: os.Getenv("COOKIE_SECURE"),
domain: os.Getenv("COOKIE_DOMAIN"),
},
sessionType: os.Getenv("SESSION_TYPE"),
database: databaseConfig{
database: os.Getenv("DATABASE_TYPE"),
dsn: ras.BuildDSN(),
},
redis: redisConfig{
host: os.Getenv("REDIS_HOST"),
password: os.Getenv("REDIS_PASSWORD"),
prefix: os.Getenv("REDIS_PREFIX"),
},
}
// create session
sess := session.Session {
CookieLifetime: ras.config.cookie.lifetime,
CookiePersist: ras.config.cookie.persist,
CookieName: ras.config.cookie.name,
SessionType: ras.config.sessionType,
CookieDomain: ras.config.cookie.domain,
}
switch ras.config.sessionType {
case "redis":
sess.RedisPool = myRedisCache.Conn
case "mysql", "postgres", "mariadb", "postgresql":
sess.DBPool = ras.DB.Pool
}
ras.Session = sess.InitSession()
ras.EncryptionKey = os.Getenv("KEY")
if ras.Debug {
var views = jet.NewSet(
jet.NewOSFileSystemLoader(fmt.Sprintf("%s/views", rootPath)),
jet.InDevelopmentMode(),
)
ras.JetViews = views
} else {
var views = jet.NewSet(
jet.NewOSFileSystemLoader(fmt.Sprintf("%s/views", rootPath)),
)
ras.JetViews = views
}
ras.createRenderer()
return nil
}
// Init creates necessary folders for our Celeritas application
func (ras *Rasant) Init(p initPaths) error {
root := p.rootPath
for _, path := range p.folderNames {
// create directory if it doesn't exist
err := ras.CreateDirIfNotExist(root + "/" + path)
if err!= nil {
return err
}
}
return nil
}
// ListenAndServe starts the web server
func (ras *Rasant) ListenAndServe() {
srv := &http.Server{
Addr: fmt.Sprintf(":%s", os.Getenv("PORT")),
ErrorLog: ras.ErrorLog,
Handler: ras.Routes,
IdleTimeout: 30 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 600 * time.Second,
}
defer ras.DB.Pool.Close()
ras.InfoLog.Printf("Listing on port %s", os.Getenv("PORT"))
err := srv.ListenAndServe()
ras.ErrorLog.Fatal(err)
}
func (ras *Rasant) checkDotEnv(path string) error {
err := ras.CreateFileIfNotExist(fmt.Sprintf("%s/.env", path))
if err != nil {
return err
}
return nil
}
func (ras *Rasant) createClientRedisCache() *cache.RedisCache {
cacheClient := cache.RedisCache{
Conn: ras.createRedisPool(),
Prefix: ras.config.redis.prefix,
}
return &cacheClient
}
func (ras *Rasant) createClientBadgerCache() *cache.BadgerCache {
cacheClient := cache.BadgerCache{
Conn: ras.createBadgerConn(),
}
return &cacheClient
}
func (ras *Rasant) createRedisPool() *redis.Pool {
return &redis.Pool{
MaxIdle: 50,
MaxActive: 10000,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", ras.config.redis.host, redis.DialPassword(ras.config.redis.password))
},
TestOnBorrow: func(conn redis.Conn, t time.Time) error {
_, err := conn.Do("PING")
return err
},
}
}
func (ras *Rasant) createBadgerConn() *badger.DB {
db, err := badger.Open(badger.DefaultOptions(ras.RootPath + "/tmp/badger"))
if err != nil {
return nil
}
return db
}
func (ras *Rasant) 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.Stdout, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
return infoLog, errorLog
}
func (ras *Rasant) createRenderer() {
myRenderer := render.Render{
Renderer: ras.config.renderer,
RootPath: ras.RootPath,
Port: ras.config.port,
JetViews: ras.JetViews,
Session: ras.Session,
}
ras.Render = &myRenderer
}
func (ras *Rasant) BuildDSN() 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"))
// we check to see if a database passsword has been supplied, since including "password=" with nothing
// after it sometimes causes postgres to fail to allow a connection.
if os.Getenv("DATABASE_PASS") != "" {
dsn = fmt.Sprintf("%s password=%s", dsn, os.Getenv("DATABASE_PASS"))
}
default:
}
return dsn
}