120 lines
1.9 KiB
Go
120 lines
1.9 KiB
Go
package application
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Mode uint
|
|
|
|
const (
|
|
Debug Mode = iota
|
|
Test
|
|
Production
|
|
)
|
|
|
|
type Version struct {
|
|
Major uint8
|
|
Minor uint8
|
|
Patch uint8
|
|
}
|
|
|
|
type AppError struct {
|
|
Error string `json:"error"`
|
|
Debug string `json:"debug"`
|
|
}
|
|
|
|
type Application struct {
|
|
version Version
|
|
urlRoot string
|
|
database *Database
|
|
engine *gin.Engine
|
|
mode Mode
|
|
}
|
|
|
|
func (a *Application) SqliteDB(path string) {
|
|
a.database = &Database{
|
|
databaseType: SQLite3,
|
|
path: path,
|
|
mode: a.mode,
|
|
}
|
|
}
|
|
|
|
func (a *Application) OpenDB() error {
|
|
return a.database.open()
|
|
}
|
|
|
|
func (a *Application) CloseDB() error {
|
|
return a.database.close()
|
|
}
|
|
|
|
func (a Application) Db() *gorm.DB {
|
|
return a.database.db
|
|
}
|
|
|
|
func (a Application) Version() string {
|
|
return fmt.Sprintf("%d.%d.%d", a.version.Major, a.version.Minor, a.version.Patch)
|
|
}
|
|
|
|
func (a Application) VersionNamespace() string {
|
|
return fmt.Sprintf("%d", a.version.Major)
|
|
}
|
|
|
|
func (a Application) UrlRoot() string {
|
|
return a.urlRoot
|
|
}
|
|
|
|
func (a Application) Engine() *gin.Engine {
|
|
return a.engine
|
|
}
|
|
|
|
func (a *Application) Run(address string) error {
|
|
return a.engine.Run(address)
|
|
}
|
|
|
|
func (a Application) Database() *Database {
|
|
return a.database
|
|
}
|
|
|
|
func (a Application) Mode() Mode {
|
|
return a.mode
|
|
}
|
|
|
|
func (a Application) NewError(error string, debug string) interface{} {
|
|
if a.mode == Debug {
|
|
return AppError{
|
|
Error: error,
|
|
Debug: debug,
|
|
}
|
|
} else {
|
|
return struct {
|
|
Error string `json:"error"`
|
|
Debug string `json:"-"`
|
|
}{error, debug}
|
|
}
|
|
}
|
|
|
|
func NewApplication(version Version, urlRoot string, mode Mode) *Application {
|
|
|
|
switch mode {
|
|
case Production:
|
|
gin.SetMode(gin.ReleaseMode)
|
|
case Test:
|
|
gin.SetMode(gin.TestMode)
|
|
}
|
|
|
|
app := Application{
|
|
version: Version{
|
|
Major: version.Major,
|
|
Minor: version.Minor,
|
|
Patch: version.Patch,
|
|
},
|
|
urlRoot: urlRoot,
|
|
engine: gin.Default(),
|
|
mode: mode,
|
|
}
|
|
|
|
return &app
|
|
}
|