57 lines
1 KiB
Go
57 lines
1 KiB
Go
package app
|
|
|
|
import (
|
|
"database/sql"
|
|
"git.katuwoss.dev/JustScreaMy/secret-santa/internal/config"
|
|
"git.katuwoss.dev/JustScreaMy/secret-santa/internal/middlewares"
|
|
"net/http"
|
|
)
|
|
|
|
type App struct {
|
|
Config config.AppConfig
|
|
DB *sql.DB
|
|
Server *http.Server
|
|
}
|
|
|
|
func NewApp(db *sql.DB, appConfig *config.AppConfig, server *http.Server) *App {
|
|
if appConfig == nil {
|
|
defaultConfig := config.NewAppConfig(nil, nil)
|
|
appConfig = &defaultConfig
|
|
}
|
|
|
|
app := &App{
|
|
Config: *appConfig,
|
|
DB: db,
|
|
}
|
|
|
|
if server == nil {
|
|
server = &http.Server{
|
|
Addr: app.Config.GenerateIP(),
|
|
Handler: app.Middlewares(app.Router()),
|
|
}
|
|
} else {
|
|
server.Handler = app.Router()
|
|
}
|
|
|
|
app.Server = server
|
|
return app
|
|
}
|
|
|
|
func (a *App) Router() http.Handler {
|
|
router := http.NewServeMux()
|
|
|
|
AddRoutes(router, a.DB)
|
|
|
|
return router
|
|
}
|
|
|
|
func (a *App) Middlewares(handler http.Handler) http.Handler {
|
|
stack := middlewares.CreateMiddlewareStack(
|
|
middlewares.Logging,
|
|
)
|
|
return stack(handler)
|
|
}
|
|
|
|
func (a *App) Start() error {
|
|
return a.Server.ListenAndServe()
|
|
}
|