forked from goffee/core
add documentation
This commit is contained in:
parent
1b23363f6f
commit
695f1f57ba
8 changed files with 116 additions and 14 deletions
57
core.go
57
core.go
|
|
@ -39,13 +39,17 @@ var basePath string
|
|||
var runMode string
|
||||
var disableEvents bool = false
|
||||
|
||||
// components_resources holds embedded file system data, typically for templates or other embedded resources.
|
||||
//
|
||||
//go:embed all:template
|
||||
var components_resources embed.FS
|
||||
|
||||
// configContainer is a configuration structure that holds request-specific configurations for the application.
|
||||
type configContainer struct {
|
||||
Request RequestConfig
|
||||
}
|
||||
|
||||
// App is a struct representing the main application container and its core components.
|
||||
type App struct {
|
||||
t int // for tracking hooks
|
||||
chain *chain
|
||||
|
|
@ -53,8 +57,10 @@ type App struct {
|
|||
Config *configContainer
|
||||
}
|
||||
|
||||
// app is a global instance of the App structure used to manage application configuration and lifecycle.
|
||||
var app *App
|
||||
|
||||
// New initializes and returns a new instance of the App structure with default configurations and chain.
|
||||
func New() *App {
|
||||
app = &App{
|
||||
chain: &chain{},
|
||||
|
|
@ -66,24 +72,29 @@ func New() *App {
|
|||
return app
|
||||
}
|
||||
|
||||
// ResolveApp returns the global instance of the App, providing access to its methods and configuration components.
|
||||
func ResolveApp() *App {
|
||||
return app
|
||||
}
|
||||
|
||||
// SetLogsDriver sets the logging driver to be used by the application.
|
||||
func (app *App) SetLogsDriver(d logger.LogsDriver) {
|
||||
logsDriver = &d
|
||||
}
|
||||
|
||||
// Bootstrap initializes the application by setting up the logger, router, and events manager.
|
||||
func (app *App) Bootstrap() {
|
||||
loggr = logger.NewLogger(*logsDriver)
|
||||
NewRouter()
|
||||
NewEventsManager()
|
||||
}
|
||||
|
||||
// RegisterTemplates initializes the application template system by embedding provided templates for rendering views.
|
||||
func (app *App) RegisterTemplates(templates_resources embed.FS) {
|
||||
NewTemplates(components_resources, templates_resources)
|
||||
}
|
||||
|
||||
// Run initializes the application's router, configures HTTPS if enabled, and starts the HTTP/HTTPS server.
|
||||
func (app *App) Run(router *httprouter.Router) {
|
||||
portNumber := os.Getenv("App_HTTP_PORT")
|
||||
if portNumber == "" {
|
||||
|
|
@ -156,6 +167,9 @@ func (app *App) Run(router *httprouter.Router) {
|
|||
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", portNumber), router))
|
||||
}
|
||||
|
||||
// RegisterRoutes sets up and registers HTTP routes and their handlers to the provided router, enabling request processing.
|
||||
// It assigns appropriate methods, controllers, and hooks, while handling core services, errors, and fallback behaviors.
|
||||
// Returns the configured router instance.
|
||||
func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httprouter.Router {
|
||||
router.PanicHandler = panicHandler
|
||||
router.NotFound = notFoundHandler{}
|
||||
|
|
@ -194,6 +208,7 @@ func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httpr
|
|||
return router
|
||||
}
|
||||
|
||||
// makeHTTPRouterHandlerFunc creates an httprouter.Handle that handles HTTP requests with the specified controller and hooks.
|
||||
func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
|
||||
|
|
@ -260,9 +275,13 @@ func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Ha
|
|||
}
|
||||
}
|
||||
|
||||
// notFoundHandler is a type that implements the http.Handler interface to handle HTTP 404 Not Found errors.
|
||||
type notFoundHandler struct{}
|
||||
|
||||
// methodNotAllowed is a type that implements http.Handler to handle HTTP 405 Method Not Allowed errors.
|
||||
type methodNotAllowed struct{}
|
||||
|
||||
// ServeHTTP handles HTTP requests by responding with a 404 status code and a JSON-formatted "Not Found" message.
|
||||
func (n notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
res := "{\"message\": \"Not Found\"}"
|
||||
|
|
@ -272,6 +291,7 @@ func (n notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
w.Write([]byte(res))
|
||||
}
|
||||
|
||||
// ServeHTTP handles HTTP requests with method not allowed status and logs the occurrence and stack trace.
|
||||
func (n methodNotAllowed) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
res := "{\"message\": \"Method not allowed\"}"
|
||||
|
|
@ -281,6 +301,7 @@ func (n methodNotAllowed) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
w.Write([]byte(res))
|
||||
}
|
||||
|
||||
// panicHandler handles panics during HTTP request processing, logs errors, and formats responses based on environment settings.
|
||||
var panicHandler = func(w http.ResponseWriter, r *http.Request, e interface{}) {
|
||||
isDebugModeStr := os.Getenv("APP_DEBUG_MODE")
|
||||
isDebugMode, err := strconv.ParseBool(isDebugModeStr)
|
||||
|
|
@ -315,10 +336,12 @@ var panicHandler = func(w http.ResponseWriter, r *http.Request, e interface{}) {
|
|||
w.Write([]byte(res))
|
||||
}
|
||||
|
||||
// UseHook registers a Hook middleware function by attaching it to the global Hooks instance.
|
||||
func UseHook(mw Hook) {
|
||||
ResolveHooks().Attach(mw)
|
||||
}
|
||||
|
||||
// Next advances to the next middleware or controller in the chain and invokes it with the given context if available.
|
||||
func (app *App) Next(c *Context) {
|
||||
app.t = app.t + 1
|
||||
n := app.chain.getByIndex(app.t)
|
||||
|
|
@ -335,14 +358,17 @@ func (app *App) Next(c *Context) {
|
|||
}
|
||||
}
|
||||
|
||||
// chain represents a sequence of nodes, where each node is an interface, used for executing a series of operations.
|
||||
type chain struct {
|
||||
nodes []interface{}
|
||||
}
|
||||
|
||||
// reset clears all nodes in the chain, resetting it to an empty state.
|
||||
func (cn *chain) reset() {
|
||||
cn.nodes = []interface{}{}
|
||||
}
|
||||
|
||||
// getByIndex retrieves an element from the chain's nodes slice by its index. Returns nil if the index is out of range.
|
||||
func (c *chain) getByIndex(i int) interface{} {
|
||||
for k := range c.nodes {
|
||||
if k == i {
|
||||
|
|
@ -353,6 +379,7 @@ func (c *chain) getByIndex(i int) interface{} {
|
|||
return nil
|
||||
}
|
||||
|
||||
// prepareChain appends all hooks from the provided list and the application's Hooks to the chain's nodes.
|
||||
func (app *App) prepareChain(hs []interface{}) {
|
||||
mw := app.hooks.GetHooks()
|
||||
for _, v := range mw {
|
||||
|
|
@ -363,6 +390,7 @@ func (app *App) prepareChain(hs []interface{}) {
|
|||
}
|
||||
}
|
||||
|
||||
// execute executes the first node in the chain, invoking it as either a Hook or Controller if applicable.
|
||||
func (cn *chain) execute(ctx *Context) {
|
||||
i := cn.getByIndex(0)
|
||||
if i != nil {
|
||||
|
|
@ -378,6 +406,7 @@ func (cn *chain) execute(ctx *Context) {
|
|||
}
|
||||
}
|
||||
|
||||
// combHandlers combines a controller and a slice of hooks into a single slice of interfaces in reversed order.
|
||||
func (app *App) combHandlers(h Controller, mw []Hook) []interface{} {
|
||||
var rev []interface{}
|
||||
for _, k := range mw {
|
||||
|
|
@ -387,6 +416,8 @@ func (app *App) combHandlers(h Controller, mw []Hook) []interface{} {
|
|||
return rev
|
||||
}
|
||||
|
||||
// getGormFunc returns a function that provides a *gorm.DB instance, ensuring gorm is enabled in the configuration.
|
||||
// If gorm is not enabled, it panics with an appropriate message.
|
||||
func getGormFunc() func() *gorm.DB {
|
||||
f := func() *gorm.DB {
|
||||
if !gormC.EnableGorm {
|
||||
|
|
@ -397,6 +428,9 @@ func getGormFunc() func() *gorm.DB {
|
|||
return f
|
||||
}
|
||||
|
||||
// NewGorm initializes and returns a new gorm.DB instance based on the selected database driver specified in environment variables.
|
||||
// Supported drivers include MySQL, PostgreSQL, and SQLite.
|
||||
// Panics if the database driver is not specified or if a connection error occurs.
|
||||
func NewGorm() *gorm.DB {
|
||||
var err error
|
||||
switch os.Getenv("DB_DRIVER") {
|
||||
|
|
@ -421,6 +455,7 @@ func NewGorm() *gorm.DB {
|
|||
return db
|
||||
}
|
||||
|
||||
// ResolveGorm initializes and returns a singleton instance of *gorm.DB, creating it if it doesn't already exist.
|
||||
func ResolveGorm() *gorm.DB {
|
||||
if db != nil {
|
||||
return db
|
||||
|
|
@ -429,6 +464,8 @@ func ResolveGorm() *gorm.DB {
|
|||
return db
|
||||
}
|
||||
|
||||
// resolveCache returns a function that provides a *Cache instance when invoked.
|
||||
// Panics if caching is not enabled in the configuration.
|
||||
func resolveCache() func() *Cache {
|
||||
f := func() *Cache {
|
||||
if !cacheC.EnableCache {
|
||||
|
|
@ -439,6 +476,8 @@ func resolveCache() func() *Cache {
|
|||
return f
|
||||
}
|
||||
|
||||
// postgresConnect establishes a connection to a PostgreSQL database using environment variables for configuration.
|
||||
// It returns a pointer to a gorm.DB instance or an error if the connection fails.
|
||||
func postgresConnect() (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=%v TimeZone=%v",
|
||||
os.Getenv("POSTGRES_HOST"),
|
||||
|
|
@ -452,6 +491,8 @@ func postgresConnect() (*gorm.DB, error) {
|
|||
return gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
}
|
||||
|
||||
// mysqlConnect establishes a connection to a MySQL database using credentials and configurations from environment variables.
|
||||
// Returns a *gorm.DB instance on success or an error if the connection fails.
|
||||
func mysqlConnect() (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v&parseTime=True&loc=Local",
|
||||
os.Getenv("MYSQL_USERNAME"),
|
||||
|
|
@ -471,6 +512,9 @@ func mysqlConnect() (*gorm.DB, error) {
|
|||
}), &gorm.Config{})
|
||||
}
|
||||
|
||||
// getJWT returns a function that initializes and provides a *JWT instance configured with environment variables.
|
||||
// The JWT instance is created using a secret signing key and a lifespan derived from the environment.
|
||||
// Panics if the signing key is not set or if the lifespan cannot be parsed.
|
||||
func getJWT() func() *JWT {
|
||||
f := func() *JWT {
|
||||
secret := os.Getenv("JWT_SECRET")
|
||||
|
|
@ -494,6 +538,7 @@ func getJWT() func() *JWT {
|
|||
return f
|
||||
}
|
||||
|
||||
// getValidator returns a closure that instantiates and provides a new instance of Validator.
|
||||
func getValidator() func() *Validator {
|
||||
f := func() *Validator {
|
||||
return &Validator{}
|
||||
|
|
@ -501,6 +546,7 @@ func getValidator() func() *Validator {
|
|||
return f
|
||||
}
|
||||
|
||||
// resloveHashing returns a function that initializes and provides a pointer to a new instance of the Hashing struct.
|
||||
func resloveHashing() func() *Hashing {
|
||||
f := func() *Hashing {
|
||||
return &Hashing{}
|
||||
|
|
@ -508,6 +554,7 @@ func resloveHashing() func() *Hashing {
|
|||
return f
|
||||
}
|
||||
|
||||
// resolveMailer initializes and returns a function that provides a singleton Mailer instance based on the configured driver.
|
||||
func resolveMailer() func() *Mailer {
|
||||
f := func() *Mailer {
|
||||
if mailer != nil {
|
||||
|
|
@ -536,6 +583,7 @@ func resolveMailer() func() *Mailer {
|
|||
return f
|
||||
}
|
||||
|
||||
// resolveEventsManager creates and returns a function that resolves the singleton instance of EventsManager.
|
||||
func resolveEventsManager() func() *EventsManager {
|
||||
f := func() *EventsManager {
|
||||
return ResolveEventsManager()
|
||||
|
|
@ -543,6 +591,7 @@ func resolveEventsManager() func() *EventsManager {
|
|||
return f
|
||||
}
|
||||
|
||||
// resolveLogger returns a function that provides access to the initialized logger instance when invoked.
|
||||
func resolveLogger() func() *logger.Logger {
|
||||
f := func() *logger.Logger {
|
||||
return loggr
|
||||
|
|
@ -550,6 +599,7 @@ func resolveLogger() func() *logger.Logger {
|
|||
return f
|
||||
}
|
||||
|
||||
// MakeDirs creates the specified directories under the base path with the provided permissions (0766).
|
||||
func (app *App) MakeDirs(dirs ...string) {
|
||||
o := syscall.Umask(0)
|
||||
defer syscall.Umask(o)
|
||||
|
|
@ -558,30 +608,37 @@ func (app *App) MakeDirs(dirs ...string) {
|
|||
}
|
||||
}
|
||||
|
||||
// SetRequestConfig sets the configuration for the request in the application instance.
|
||||
func (app *App) SetRequestConfig(r RequestConfig) {
|
||||
requestC = r
|
||||
}
|
||||
|
||||
// SetGormConfig sets the GormConfig for the application, overriding the current configuration with the provided value.
|
||||
func (app *App) SetGormConfig(g GormConfig) {
|
||||
gormC = g
|
||||
}
|
||||
|
||||
// SetCacheConfig sets the cache configuration for the application using the provided CacheConfig parameter.
|
||||
func (app *App) SetCacheConfig(c CacheConfig) {
|
||||
cacheC = c
|
||||
}
|
||||
|
||||
// SetBasePath sets the base path for the application, which is used as a prefix for file and directory operations.
|
||||
func (app *App) SetBasePath(path string) {
|
||||
basePath = path
|
||||
}
|
||||
|
||||
// SetRunMode sets the application run mode to the specified value.
|
||||
func (app *App) SetRunMode(runmode string) {
|
||||
runMode = runmode
|
||||
}
|
||||
|
||||
// DisableEvents sets the global variable `disableEvents` to true, disabling the handling or triggering of events.
|
||||
func DisableEvents() {
|
||||
disableEvents = true
|
||||
}
|
||||
|
||||
// EnableEvents sets the global variable `disableEvents` to false, effectively enabling event handling.
|
||||
func EnableEvents() {
|
||||
disableEvents = false
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue