diff --git a/.gitignore b/.gitignore index e6c34ba..191579c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ tmp -.DS_STore \ No newline at end of file +.DS_STore +.idea diff --git a/README.md b/README.md index 42f1bf9..73e7ccc 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ -# GoCondor Core -![Build Status](https://github.com/gocondor/core/actions/workflows/build-main.yml/badge.svg) ![Test Status](https://github.com/gocondor/core/actions/workflows/test-main.yml/badge.svg) [![Coverage Status](https://coveralls.io/repos/github/gocondor/core/badge.svg?branch=main)](https://coveralls.io/github/gocondor/core?branch=main&cache=false) [![GoDoc](https://godoc.org/github.com/gocondor/core?status.svg)](https://godoc.org/github.com/gocondor/core) [![Go Report Card](https://goreportcard.com/badge/github.com/gocondor/core)](https://goreportcard.com/report/github.com/gocondor/core) +# Goffee Core -The core packages of GoCondor framework +The core packages of Goffee framework diff --git a/cache.go b/cache.go index 04e818c..4f32bcd 100644 --- a/cache.go +++ b/cache.go @@ -16,6 +16,9 @@ type Cache struct { redis *redis.Client } +// NewCache initializes a new Cache instance with the provided configuration and connects to a Redis database. +// If caching is enabled in the provided configuration but the connection to Redis fails, it causes a panic. +// Returns a pointer to the initialized Cache structure. func NewCache(cacheConfig CacheConfig) *Cache { ctx = context.Background() dbStr := os.Getenv("REDIS_DB") @@ -40,6 +43,7 @@ func NewCache(cacheConfig CacheConfig) *Cache { } } +// Set stores a key-value pair in the Redis cache with no expiration. Returns an error if the operation fails. func (c *Cache) Set(key string, value string) error { err := c.redis.Set(ctx, key, value, 0).Err() if err != nil { @@ -48,6 +52,8 @@ func (c *Cache) Set(key string, value string) error { return nil } +// SetWithExpiration stores a key-value pair in the cache with a specified expiration duration. +// Returns an error if the operation fails. func (c *Cache) SetWithExpiration(key string, value string, expiration time.Duration) error { err := c.redis.Set(ctx, key, value, expiration).Err() if err != nil { @@ -56,6 +62,7 @@ func (c *Cache) SetWithExpiration(key string, value string, expiration time.Dura return nil } +// Get retrieves the value associated with the provided key from the cache. Returns an error if the operation fails. func (c *Cache) Get(key string) (string, error) { result, err := c.redis.Get(ctx, key).Result() if err != nil { @@ -64,6 +71,7 @@ func (c *Cache) Get(key string) (string, error) { return result, nil } +// Delete removes the specified key from the cache and returns an error if the operation fails. func (c *Cache) Delete(key string) error { err := c.redis.Del(ctx, key).Err() if err != nil { diff --git a/config.go b/config.go index f214e84..c481de2 100644 --- a/config.go +++ b/config.go @@ -22,6 +22,10 @@ type GormConfig struct { EnableGorm bool } +type QueueConfig struct { + EnableQueue bool +} + type CacheConfig struct { EnableCache bool } diff --git a/context.go b/context.go index ad1321d..9015159 100644 --- a/context.go +++ b/context.go @@ -19,6 +19,7 @@ import ( "syscall" "git.smarteching.com/goffee/core/logger" + "github.com/hibiken/asynq" "gorm.io/gorm" ) @@ -53,7 +54,11 @@ func (c *Context) Next() { } func (c *Context) prepare(ctx *Context) { - ctx.Request.httpRequest.ParseMultipartForm(int64(app.Config.Request.MaxUploadFileSize)) + // Only parse multipart form if it hasn't been parsed already + // This prevents race conditions when multiple goroutines might access the same request + if ctx.Request.httpRequest.MultipartForm == nil { + ctx.Request.httpRequest.ParseMultipartForm(int64(app.Config.Request.MaxUploadFileSize)) + } } func (c *Context) GetPathParam(key string) interface{} { @@ -68,8 +73,9 @@ func (c *Context) RequestParamExists(key string) bool { return c.Request.httpRequest.Form.Has(key) } -func (c *Context) GetRequesForm() interface{} { - return c.Request.httpRequest.Form +func (c *Context) GetRequesForm(key string) interface{} { + c.Request.httpRequest.ParseForm() + return c.Request.httpRequest.Form[key] } func (c *Context) GetRequesBodyMap() map[string]interface{} { @@ -111,34 +117,51 @@ func (c *Context) GetCookie() (UserCookie, error) { return user, nil } -func (c *Context) GetUploadedFile(name string) *UploadedFileInfo { +func (c *Context) GetQueueClient() *asynq.Client { + + redisAddr := fmt.Sprintf("%v:%v", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PORT")) + client := asynq.NewClient(asynq.RedisClientOpt{Addr: redisAddr}) + + return client +} + +func (c *Context) GetUploadedFile(name string) (*UploadedFileInfo, error) { file, fileHeader, err := c.Request.httpRequest.FormFile(name) if err != nil { - panic(fmt.Sprintf("error with file,[%v]", err.Error())) + return nil, fmt.Errorf("error retrieving file: %v", err) } defer file.Close() + + // Extract the file extension ext := strings.TrimPrefix(path.Ext(fileHeader.Filename), ".") tmpFilePath := filepath.Join(os.TempDir(), fileHeader.Filename) tmpFile, err := os.Create(tmpFilePath) if err != nil { - panic(fmt.Sprintf("error with file,[%v]", err.Error())) + return nil, fmt.Errorf("error creating temporary file: %v", err) } + defer tmpFile.Close() + // Copy the uploaded file content to the temporary file buff := make([]byte, 100) for { n, err := file.Read(buff) if err != nil && err != io.EOF { - panic("error with uploaded file") + return nil, fmt.Errorf("error reading uploaded file: %v", err) } if n == 0 { break } - n, _ = tmpFile.Write(buff[:n]) + _, err = tmpFile.Write(buff[:n]) + if err != nil { + return nil, fmt.Errorf("error writing to temporary file: %v", err) + } } + + // Get file info for the temporary file tmpFileInfo, err := os.Stat(tmpFilePath) if err != nil { - panic(fmt.Sprintf("error with file,[%v]", err.Error())) + return nil, fmt.Errorf("error getting file info: %v", err) } - defer tmpFile.Close() + uploadedFileInfo := &UploadedFileInfo{ FullPath: tmpFilePath, Name: fileHeader.Filename, @@ -146,7 +169,7 @@ func (c *Context) GetUploadedFile(name string) *UploadedFileInfo { Extension: ext, Size: int(tmpFileInfo.Size()), } - return uploadedFileInfo + return uploadedFileInfo, nil } func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error { @@ -175,7 +198,7 @@ func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error { for { n, err := srcFile.Read(buff) if err != nil && err != io.EOF { - panic(fmt.Sprintf("error moving file %v", sourceFilePath)) + return fmt.Errorf("error moving file: %v", sourceFilePath) } if n == 0 { break @@ -219,7 +242,7 @@ func (c *Context) CopyFile(sourceFilePath string, destFolderPath string) error { for { n, err := srcFile.Read(buff) if err != nil && err != io.EOF { - panic(fmt.Sprintf("error moving file %v", sourceFilePath)) + return fmt.Errorf("error moving file: %v", sourceFilePath) } if n == 0 { break diff --git a/cookies.go b/cookies.go index ce17dd2..4e51470 100644 --- a/cookies.go +++ b/cookies.go @@ -21,19 +21,24 @@ import ( "strings" ) +// ErrValueTooLong indicates that the cookie value exceeds the allowed length limit. +// ErrInvalidValue signifies that the cookie value is in an invalid format. var ( ErrValueTooLong = errors.New("cookie value too long") ErrInvalidValue = errors.New("invalid cookie value") ) -// Declare the User type. +// UserCookie represents a structure to hold user-specific data stored in a cookie, including Email and Token fields. type UserCookie struct { Email string Token string } +// secretcookie is a global variable used to store the decoded secret key for encrypting and decrypting cookies. var secretcookie []byte +// GetCookie retrieves and decrypts the user cookie from the provided HTTP request and returns it as a UserCookie. +// Returns an error if the cookie retrieval, decryption, or decoding process fails. func GetCookie(r *http.Request) (UserCookie, error) { var err error @@ -78,6 +83,7 @@ func GetCookie(r *http.Request) (UserCookie, error) { } +// SetCookie sets an encrypted cookie with a user's email and token, using gob encoding for data serialization. func SetCookie(w http.ResponseWriter, email string, token string) error { // Initialize a User struct containing the data that we want to store in the // cookie. @@ -138,6 +144,8 @@ func SetCookie(w http.ResponseWriter, email string, token string) error { return nil } +// CookieWrite writes a secure HTTP cookie to the response writer after base64 encoding its value. +// Returns ErrValueTooLong if the cookie string exceeds the 4096-byte size limit. func CookieWrite(w http.ResponseWriter, cookie http.Cookie) error { // Encode the cookie value using base64. cookie.Value = base64.URLEncoding.EncodeToString([]byte(cookie.Value)) @@ -154,6 +162,8 @@ func CookieWrite(w http.ResponseWriter, cookie http.Cookie) error { return nil } +// CookieRead retrieves a base64-encoded cookie value by name from the HTTP request and decodes it. +// Returns the decoded value as a string or an error if the cookie is not found or the value is invalid. func CookieRead(r *http.Request, name string) (string, error) { // Read the cookie as normal. cookie, err := r.Cookie(name) @@ -173,6 +183,9 @@ func CookieRead(r *http.Request, name string) (string, error) { return string(value), nil } +// CookieWriteEncrypted encrypts the cookie's value using AES-GCM and writes it to the HTTP response writer. +// The cookie name is authenticated along with its value. +// It returns an error if encryption fails or the cookie exceeds the maximum allowed length. func CookieWriteEncrypted(w http.ResponseWriter, cookie http.Cookie, secretKey []byte) error { // Create a new AES cipher block from the secret key. block, err := aes.NewCipher(secretKey) @@ -213,6 +226,8 @@ func CookieWriteEncrypted(w http.ResponseWriter, cookie http.Cookie, secretKey [ return CookieWrite(w, cookie) } +// CookieReadEncrypted reads an encrypted cookie, decrypts its value using AES-GCM, and validates its name before returning. +// Returns the plaintext cookie value or an error if decryption or validation fails. func CookieReadEncrypted(r *http.Request, name string, secretKey []byte) (string, error) { // Read the encrypted value from the cookie as normal. encryptedValue, err := CookieRead(r, name) diff --git a/core.go b/core.go index d449635..3846432 100644 --- a/core.go +++ b/core.go @@ -6,6 +6,7 @@ package core import ( + "context" "embed" "fmt" "log" @@ -39,22 +40,34 @@ 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 + t int // for tracking hooks (deprecated - maintained for backward compatibility) chain *chain hooks *Hooks Config *configContainer } +// requestContext holds request-specific chain execution state +type requestContext struct { + chainIndex int + chainNodes []interface{} +} + +// 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 +79,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 == "" { @@ -93,7 +111,7 @@ func (app *App) Run(router *httprouter.Router) { // check if template engine is enable TemplateEnableStr := os.Getenv("TEMPLATE_ENABLE") - if TemplateEnableStr == "" { + if "" == TemplateEnableStr { TemplateEnableStr = "false" } TemplateEnable, _ := strconv.ParseBool(TemplateEnableStr) @@ -102,13 +120,33 @@ func (app *App) Run(router *httprouter.Router) { router.ServeFiles("/public/*filepath", http.Dir("storage/public")) } + // check if app engine is enable + AppEnableStr := os.Getenv("APP_ENABLE") + if "" == AppEnableStr { + AppEnableStr = "false" + } + AppEnable, _ := strconv.ParseBool(AppEnableStr) + if AppEnable { + router.ServeFiles("/app/*filepath", http.Dir("storage/app")) + } + + // check if app engine is enable + CDNEnableStr := os.Getenv("CDN_ENABLE") + if "" == CDNEnableStr { + CDNEnableStr = "false" + } + CDNEnable, _ := strconv.ParseBool(CDNEnableStr) + if CDNEnable { + router.ServeFiles("/cdn/*filepath", http.Dir("storage/cdn")) + } + useHttpsStr := os.Getenv("App_USE_HTTPS") if useHttpsStr == "" { useHttpsStr = "false" } useHttps, _ := strconv.ParseBool(useHttpsStr) - if runMode == "dev" { + if "dev" == runMode { fmt.Printf("Welcome to Goffee\n") if useHttps { fmt.Printf("Listening on https \nWaiting for requests...\n") @@ -156,6 +194,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,12 +235,28 @@ 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) { - + // Create request-specific chain state + reqCtx := &requestContext{ + chainIndex: 0, + } + + // Prepare the chain nodes for this request + mw := app.hooks.GetHooks() + for _, v := range mw { + reqCtx.chainNodes = append(reqCtx.chainNodes, v) + } + rhs := app.combHandlers(h, ms) + for _, v := range rhs { + reqCtx.chainNodes = append(reqCtx.chainNodes, v) + } + + // Store chain state in request context ctx := &Context{ Request: &Request{ - httpRequest: r, + httpRequest: r.WithContext(context.WithValue(r.Context(), "goffeeChain", reqCtx)), httpPathParams: ps, }, Response: &Response{ @@ -222,15 +279,20 @@ func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Ha } ctx.prepare(ctx) - rhs := app.combHandlers(h, ms) - app.prepareChain(rhs) - app.t = 0 - app.chain.execute(ctx) + + // Execute the first handler in the chain + if len(reqCtx.chainNodes) > 0 { + n := reqCtx.chainNodes[0] + if f, ok := n.(Hook); ok { + f(ctx) + } else if ff, ok := n.(Controller); ok { + ff(ctx) + } + } for _, header := range ctx.Response.headers { w.Header().Add(header.key, header.val) } - logger.CloseLogsFile() var ct string if ctx.Response.overrideContentType != "" { ct = ctx.Response.overrideContentType @@ -245,7 +307,7 @@ func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Ha w.WriteHeader(ctx.Response.statusCode) } if ctx.Response.redirectTo != "" { - http.Redirect(w, r, ctx.Response.redirectTo, http.StatusPermanentRedirect) + http.Redirect(w, r, ctx.Response.redirectTo, http.StatusTemporaryRedirect) } else { w.Write(ctx.Response.body) } @@ -260,27 +322,33 @@ 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\"}" loggr.Error("Not Found") - loggr.Error(debug.Stack()) + //loggr.Error(debug.Stack()) w.Header().Add(CONTENT_TYPE, CONTENT_TYPE_JSON) 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\"}" loggr.Error("Method not allowed") - loggr.Error(debug.Stack()) + //loggr.Error(debug.Stack()) w.Header().Add(CONTENT_TYPE, CONTENT_TYPE_JSON) 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) @@ -303,7 +371,7 @@ var panicHandler = func(w http.ResponseWriter, r *http.Request, e interface{}) { shrtMsg := fmt.Sprintf("%v", e) loggr.Error(shrtMsg) fmt.Println(shrtMsg) - loggr.Error(string(debug.Stack())) + //loggr.Error(string(debug.Stack())) var res string if env.GetVarOtherwiseDefault("APP_ENV", "local") == PRODUCTION { res = "{\"message\": \"internal error\"}" @@ -315,34 +383,53 @@ 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) - if n != nil { - f, ok := n.(Hook) - if ok { - f(c) - } else { - ff, ok := n.(Controller) - if ok { + // Get request-specific chain state from context + if reqCtx, ok := c.Request.httpRequest.Context().Value("goffeeChain").(*requestContext); ok { + reqCtx.chainIndex++ + if reqCtx.chainIndex < len(reqCtx.chainNodes) { + n := reqCtx.chainNodes[reqCtx.chainIndex] + if f, ok := n.(Hook); ok { + f(c) + } else if ff, ok := n.(Controller); ok { ff(c) } } + } else { + // Fallback to old behavior (not thread-safe) + app.t = app.t + 1 + n := app.chain.getByIndex(app.t) + if n != nil { + f, ok := n.(Hook) + if ok { + f(c) + } else { + ff, ok := n.(Controller) + if ok { + ff(c) + } + } + } } } +// 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 +440,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 +451,18 @@ func (app *App) prepareChain(hs []interface{}) { } } +// prepareRequestChain prepares a request-specific chain to avoid race conditions +func (app *App) prepareRequestChain(requestChain *chain, hs []interface{}) { + mw := app.hooks.GetHooks() + for _, v := range mw { + requestChain.nodes = append(requestChain.nodes, v) + } + for _, v := range hs { + requestChain.nodes = append(requestChain.nodes, v) + } +} + +// 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 +478,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 +488,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 +500,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 +527,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 +536,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 +548,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 +563,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 +584,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 +610,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 +618,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 +626,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 +655,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 +663,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 +671,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 +680,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 } diff --git a/go.mod b/go.mod index 2c18ebd..793079f 100644 --- a/go.mod +++ b/go.mod @@ -4,49 +4,61 @@ replace git.smarteching.com/goffee/core/logger => ./logger replace git.smarteching.com/goffee/core/env => ./env -go 1.23.1 +go 1.25.0 require ( git.smarteching.com/zeni/go-chart/v2 v2.1.4 + git.smarteching.com/zeni/go-charts/v2 v2.6.11 github.com/brianvoe/gofakeit/v6 v6.21.0 - github.com/golang-jwt/jwt/v5 v5.0.0 - github.com/google/uuid v1.3.0 + github.com/golang-jwt/jwt/v5 v5.3.1 + github.com/google/uuid v1.6.0 github.com/harranali/mailing v1.2.0 + github.com/hibiken/asynq v0.26.0 github.com/joho/godotenv v1.5.1 github.com/julienschmidt/httprouter v1.3.0 - github.com/redis/go-redis/v9 v9.0.5 - golang.org/x/crypto v0.11.0 - gorm.io/driver/mysql v1.5.1 - gorm.io/driver/postgres v1.5.2 - gorm.io/driver/sqlite v1.5.2 - gorm.io/gorm v1.25.2 + github.com/redis/go-redis/v9 v9.19.0 + golang.org/x/crypto v0.50.0 + gorm.io/driver/mysql v1.6.0 + gorm.io/driver/postgres v1.6.0 + gorm.io/driver/sqlite v1.6.0 + gorm.io/gorm v1.31.1 ) require ( + filippo.io/edwards25519 v1.2.0 // indirect github.com/SparkPost/gosparkpost v0.2.0 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/go-chi/chi/v5 v5.0.8 // indirect - github.com/go-sql-driver/mysql v1.7.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-chi/chi/v5 v5.2.5 // indirect + github.com/go-sql-driver/mysql v1.10.0 // indirect github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect - github.com/jackc/pgx/v5 v5.3.1 // indirect - github.com/json-iterator/go v1.1.10 // indirect - github.com/mailgun/mailgun-go/v4 v4.10.0 // indirect - github.com/mattn/go-sqlite3 v1.14.17 // indirect - github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect - github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.9.2 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/mailgun/errors v0.5.0 // indirect + github.com/mailgun/mailgun-go/v4 v4.23.0 // indirect + github.com/mattn/go-sqlite3 v1.14.44 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/robfig/cron/v3 v3.0.1 // indirect github.com/sendgrid/rest v2.6.9+incompatible // indirect - github.com/sendgrid/sendgrid-go v3.12.0+incompatible // indirect - golang.org/x/image v0.21.0 // indirect - golang.org/x/net v0.10.0 // indirect - golang.org/x/text v0.19.0 // indirect + github.com/sendgrid/sendgrid-go v3.16.1+incompatible // indirect + github.com/spf13/cast v1.10.0 // indirect + go.uber.org/atomic v1.11.0 // indirect + golang.org/x/image v0.39.0 // indirect + golang.org/x/net v0.53.0 // indirect + golang.org/x/sync v0.20.0 // indirect + golang.org/x/sys v0.43.0 // indirect + golang.org/x/text v0.36.0 // indirect + golang.org/x/time v0.15.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect ) require ( - github.com/cespare/xxhash/v2 v2.2.0 // indirect - github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/go-ozzo/ozzo-validation v3.6.0+incompatible github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect diff --git a/go.sum b/go.sum index 21aed15..441135c 100644 --- a/go.sum +++ b/go.sum @@ -1,53 +1,59 @@ +filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= +filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= git.smarteching.com/zeni/go-chart/v2 v2.1.4 h1:pF06+F6eqJLIG8uMiTVPR5TygPGMjM/FHMzTxmu5V/Q= git.smarteching.com/zeni/go-chart/v2 v2.1.4/go.mod h1:b3ueW9h3pGGXyhkormZAvilHaG4+mQti+bMNPdQBeOQ= +git.smarteching.com/zeni/go-charts/v2 v2.6.11 h1:9udzlv3uxGXszpplfkL5IaTUrgkNj++KwhbaN1vVEqI= +git.smarteching.com/zeni/go-charts/v2 v2.6.11/go.mod h1:3OpRPSXg7Qx4zcgsmwsC9ZFB9/wAkGSbnXf1wIbHYCg= github.com/SparkPost/gosparkpost v0.2.0 h1:yzhHQT7cE+rqzd5tANNC74j+2x3lrPznqPJrxC1yR8s= github.com/SparkPost/gosparkpost v0.2.0/go.mod h1:S9WKcGeou7cbPpx0kTIgo8Q69WZvUmVeVzbD+djalJ4= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/brianvoe/gofakeit/v6 v6.21.0 h1:tNkm9yxEbpuPK8Bx39tT4sSc5i9SUGiciLdNix+VDQY= github.com/brianvoe/gofakeit/v6 v6.21.0/go.mod h1:Ow6qC71xtwm79anlwKRlWZW6zVq9D2XHE4QSSMP/rU8= -github.com/bsm/ginkgo/v2 v2.7.0 h1:ItPMPH90RbmZJt5GtkcNvIRuGEdwlBItdNVoyzaNQao= -github.com/bsm/ginkgo/v2 v2.7.0/go.mod h1:AiKlXPm7ItEHNc/2+OkrNG4E0ITzojb9/xWzvQ9XZ9w= -github.com/bsm/gomega v1.26.0 h1:LhQm+AFcgV2M0WyKroMASzAzCAJVpAxQXv4SaI9a69Y= -github.com/bsm/gomega v1.26.0/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/buger/jsonparser v1.0.0/go.mod h1:tgcrVJ81GPSF0mz+0nu1Xaz0fazGPrmmJfJtxjbHhUQ= github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a/go.mod h1:2GxOXOlEPAMFPfp014mK1SWq8G8BN8o7/dfYqJrVGn8= -github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= -github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51 h1:0JZ+dUmQeA8IIVUMzysrX4/AKuQwWhV2dYQuPZdvdSQ= -github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51/go.mod h1:Yg+htXGokKKdzcwhuNDwVvN+uBxDGXJ7G/VN1d8fa64= -github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 h1:JWuenKqqX8nojtoVVWjGfOF9635RETekkoH6Cc9SX0A= -github.com/facebookgo/stack v0.0.0-20160209184415-751773369052/go.mod h1:UbMTZqLaRiH3MsBH8va0n7s1pQYcu3uTb8G4tygF4Zg= -github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870 h1:E2s37DuLxFhQDg5gKsWoLBOB0n+ZW8s599zru8FJ2/Y= -github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870/go.mod h1:5tD+neXqOorC30/tWg0LCSkrqj/AR6gu8yY8/fpw1q0= -github.com/go-chi/chi/v5 v5.0.8 h1:lD+NLqFcAi1ovnVZpsnObHGW4xb4J8lNmoYVfECH1Y0= -github.com/go-chi/chi/v5 v5.0.8/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= +github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= github.com/go-ozzo/ozzo-validation v3.6.0+incompatible h1:msy24VGS42fKO9K1vLz82/GeYW1cILu7Nuuj1N3BBkE= github.com/go-ozzo/ozzo-validation v3.6.0+incompatible/go.mod h1:gsEKFIVnabGBt6mXmxK0MoFy+cZoTJY6mu5Ll3LVLBU= -github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= -github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw= +github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/go-test/deep v1.0.2/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= github.com/gogs/chardet v0.0.0-20150115103509-2404f7772561/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14= -github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE= -github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/harranali/mailing v1.2.0 h1:ihIyJwB8hyRVcdk+v465wk1PHMrSrgJqo/kMd+gZClY= github.com/harranali/mailing v1.2.0/go.mod h1:4a5N3yG98pZKluMpmcYlTtll7bisvOfGQEMIng3VQk4= +github.com/hibiken/asynq v0.26.0 h1:1Zxr92MlDnb1Zt/QR5g2vSCqUS03i95lUfqx5X7/wrw= +github.com/hibiken/asynq v0.26.0/go.mod h1:Qk4e57bTnWDoyJ67VkchuV6VzSM9IQW2nPvAGuDyw58= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= -github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.3.1 h1:Fcr8QJ1ZeLi5zsPZqQeUZhNhxfkkKBOgJuYkJHoBOtU= -github.com/jackc/pgx/v5 v5.3.1/go.mod h1:t3JDKnCBlYIc0ewLF0Q7B8MXmoIaBOZj/ic7iHozM/8= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= +github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jaytaylor/html2text v0.0.0-20190408195923-01ec452cbe43/go.mod h1:CVKlgaMiht+LXvHG173ujK6JUhZXKb2u/BQtjPDIvyk= github.com/jhillyerd/enmime v0.8.0/go.mod h1:MBHs3ugk03NGjMM6PuRynlKf+HA5eSillZ+TRCm73AE= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= @@ -56,64 +62,94 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= +github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/mailgun/mailgun-go/v4 v4.10.0 h1:e5LVsxpqjOYRyaOWifrJORoLQZTYDP+g4ljfmf9G2zE= -github.com/mailgun/mailgun-go/v4 v4.10.0/go.mod h1:L9s941Lgk7iB3TgywTPz074pK2Ekkg4kgbnAaAyJ2z8= +github.com/mailgun/errors v0.5.0 h1:pLQo8uhAdORsjN69mGixSr0pGs46z/BW/FQXd8HG1VM= +github.com/mailgun/errors v0.5.0/go.mod h1:+2nrgY77E0vDkG4ErehpcpbSkMLkseJzKbrva89WeSs= +github.com/mailgun/mailgun-go/v4 v4.23.0 h1:jPEMJzzin2s7lvehcfv/0UkyBu18GvcURPr2+xtZRbk= +github.com/mailgun/mailgun-go/v4 v4.23.0/go.mod h1:imTtizoFtpfZqPqGP8vltVBB6q9yWcv6llBhfFeElZU= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM= -github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8= +github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/redis/go-redis/v9 v9.0.5 h1:CuQcn5HIEeK7BgElubPP8CGtE0KakrnbBSTLjathl5o= -github.com/redis/go-redis/v9 v9.0.5/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk= +github.com/redis/go-redis/v9 v9.19.0 h1:XPVaaPSnG6RhYf7p+rmSa9zZfeVAnWsH5h3lxthOm/k= +github.com/redis/go-redis/v9 v9.19.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA= +github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= +github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/saintfish/chardet v0.0.0-20120816061221-3af4cd4741ca/go.mod h1:uugorj2VCxiV1x+LzaIdVa9b4S4qGAcH6cbhh4qVxOU= github.com/sendgrid/rest v2.6.9+incompatible h1:1EyIcsNdn9KIisLW50MKwmSRSK+ekueiEMJ7NEoxJo0= github.com/sendgrid/rest v2.6.9+incompatible/go.mod h1:kXX7q3jZtJXK5c5qK83bSGMdV6tsOE70KbHoqJls4lE= -github.com/sendgrid/sendgrid-go v3.12.0+incompatible h1:/N2vx18Fg1KmQOh6zESc5FJB8pYwt5QFBDflYPh1KVg= -github.com/sendgrid/sendgrid-go v3.12.0+incompatible/go.mod h1:QRQt+LX/NmgVEvmdRw0VT/QgUn499+iza2FnDca9fg8= +github.com/sendgrid/sendgrid-go v3.16.1+incompatible h1:zWhTmB0Y8XCDzeWIm2/BIt1GjJohAA0p6hVEaDtHWWs= +github.com/sendgrid/sendgrid-go v3.16.1+incompatible/go.mod h1:QRQt+LX/NmgVEvmdRw0VT/QgUn499+iza2FnDca9fg8= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= -golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= -golang.org/x/image v0.21.0 h1:c5qV36ajHpdj4Qi0GnE0jUc/yuo33OLFaa0d+crTD5s= -golang.org/x/image v0.21.0/go.mod h1:vUbsLavqK/W303ZroQQVKQ+Af3Yl6Uz1Ppu5J/cLz78= +golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= +golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= +golang.org/x/image v0.39.0 h1:skVYidAEVKgn8lZ602XO75asgXBgLj9G/FE3RbuPFww= +golang.org/x/image v0.39.0/go.mod h1:sIbmppfU+xFLPIG0FoVUTvyBMmgng1/XAMhQ2ft0hpA= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= +golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= +golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= -golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= +golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gorm.io/driver/mysql v1.5.1 h1:WUEH5VF9obL/lTtzjmML/5e6VfFR/788coz2uaVCAZw= -gorm.io/driver/mysql v1.5.1/go.mod h1:Jo3Xu7mMhCyj8dlrb3WoCaRd1FhsVh+yMXb1jUInf5o= -gorm.io/driver/postgres v1.5.2 h1:ytTDxxEv+MplXOfFe3Lzm7SjG09fcdb3Z/c056DTBx0= -gorm.io/driver/postgres v1.5.2/go.mod h1:fmpX0m2I1PKuR7mKZiEluwrP3hbs+ps7JIGMUBpCgl8= -gorm.io/driver/sqlite v1.5.2 h1:TpQ+/dqCY4uCigCFyrfnrJnrW9zjpelWVoEVNy5qJkc= -gorm.io/driver/sqlite v1.5.2/go.mod h1:qxAuCol+2r6PannQDpOP1FP6ag3mKi4esLnB/jHed+4= -gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= -gorm.io/gorm v1.25.2 h1:gs1o6Vsa+oVKG/a9ElL3XgyGfghFfkKA2SInQaCyMho= -gorm.io/gorm v1.25.2/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= +gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg= +gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo= +gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4= +gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo= +gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= +gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= +gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg= +gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= diff --git a/graph.go b/graph.go index 1ca21b8..1677229 100644 --- a/graph.go +++ b/graph.go @@ -11,6 +11,7 @@ import ( "strings" "git.smarteching.com/zeni/go-chart/v2" + "git.smarteching.com/zeni/go-charts/v2" "github.com/julienschmidt/httprouter" ) @@ -44,7 +45,7 @@ func Graph(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { qtyl := len(labels) qtyv := len(values) - // cjeck qty and equal values from url + // check qty and equal values from url if qtyl < 2 { fmt.Fprintf(w, "Missing captions in pie") return @@ -85,9 +86,9 @@ func Graph(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { qtyl := len(labels) qtyv := len(values) - // cjeck qty and equal values from url + // check qty and equal values from url if qtyl < 2 { - fmt.Fprintf(w, "Missing captions in pie") + fmt.Fprintf(w, "Missing captions in bar") return } if qtyv != qtyl { @@ -116,6 +117,83 @@ func Graph(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { fmt.Printf("Error rendering pie chart: %v\n", err) } + // case multiple graph bar + case "mbar": + + queryValues := r.URL.Query() + labels := strings.Split(queryValues.Get("l"), "|") + values := strings.Split(queryValues.Get("v"), "|") + options := strings.Split(queryValues.Get("o"), "|") + + qtyl := len(labels) + qtyv := len(values) + qtyo := len(options) + + // check qty and equal values from url + if qtyl < 2 { + fmt.Fprintf(w, "Missing captions in bar") + return + } + if qtyv < 2 { + fmt.Fprintf(w, "Missing values in bar") + return + } + if qtyo < 2 { + fmt.Fprintf(w, "Missing options in bar") + return + } + + valuest := [][]float64{ + { + 2.0, + 4.9, + 7.0, + 23.2, + 25.6, + 76.7, + 135.6, + 162.2, + 32.6, + }, + { + 2.6, + 5.9, + 9.0, + 26.4, + 28.7, + 70.7, + 175.6, + 182.2, + 48.7, + }, + } + p, err := charts.BarRender( + valuest, + charts.XAxisDataOptionFunc([]string{ + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + }), + charts.LegendLabelsOptionFunc(labels, charts.PositionRight), + ) + if err != nil { + panic(err) + } + + buf, err := p.Bytes() + + w.Header().Set("Content-Type", "image/png") + w.Write(buf) + if err != nil { + fmt.Printf("Error rendering pie chart: %v\n", err) + } + default: fmt.Fprintf(w, "Unknown graph %s!\n", kindg) } diff --git a/logger/logger.go b/logger/logger.go index 4746c9f..fd56eba 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -1,4 +1,4 @@ -// Copyright 2021 Harran Ali . All rights reserved. +// Copyright (c) 2026 Zeni Kim // Use of this source code is governed by MIT-style // license that can be found in the LICENSE file. @@ -8,16 +8,68 @@ import ( "io" "log" "os" + "strings" ) // logs file var logsFile *os.File +// ANSI color codes for terminal output +const ( + colorReset = "\033[0m" + colorRed = "\033[31m" + colorYellow = "\033[33m" + colorBlue = "\033[34m" + colorCyan = "\033[36m" +) + +// Level represents a log severity level. +type Level int + +const ( + DEBUG Level = iota + INFO + WARNING + ERROR +) + +// String returns the string representation of a log level. +func (l Level) String() string { + switch l { + case DEBUG: + return "debug" + case INFO: + return "info" + case WARNING: + return "warning" + case ERROR: + return "error" + default: + return "unknown" + } +} + +// coloredWriter wraps an io.Writer and replaces plain log prefixes with ANSI-colored ones +// in the output stream. The original bytes pass through unmodified to any additional writers. +type coloredWriter struct { + writer io.Writer + plain string + colored string +} + +func (w *coloredWriter) Write(p []byte) (n int, err error) { + // Replace the plain prefix with the colored version in the output + colored := strings.Replace(string(p), w.plain, w.colored, 1) + return w.writer.Write([]byte(colored)) +} + type Logger struct { + minLevel Level infoLogger *log.Logger warningLogger *log.Logger errorLogger *log.Logger debugLogger *log.Logger + file *os.File } var l *Logger @@ -40,9 +92,36 @@ func (f LogFileDriver) GetTarget() interface{} { return f.FilePath } +// levelPrefixes returns the plain and colored (with ANSI escapes) prefix strings for a given level. +func levelPrefixes(level Level) (plain, colored string) { + switch level { + case INFO: + return "info: ", colorBlue + "INFO" + colorReset + ": " + case DEBUG: + return "debug: ", colorCyan + "DEBUG" + colorReset + ": " + case WARNING: + return "warning: ", colorYellow + "WARNING" + colorReset + ": " + case ERROR: + return "error: ", colorRed + "ERROR" + colorReset + ": " + default: + return "info: ", "INFO: " + } +} + +// NewLogger creates a new Logger with the given driver and a minimum level of DEBUG (all levels logged). func NewLogger(driver LogsDriver) *Logger { + stdoutEnabled := os.Getenv("LOG_STDOUT_ENABLE") == "true" + return NewLoggerWithStdout(driver, DEBUG, stdoutEnabled) +} + +// NewLoggerWithStdout creates a new Logger with the given driver, minimum log level, +// and optionally writes to stdout in addition to the target file. +// When stdoutEnabled is true, log messages are written to both the target and stdout. +// ANSI color codes are applied to log prefixes in terminal output only. +func NewLoggerWithStdout(driver LogsDriver, minLevel Level, stdoutEnabled bool) *Logger { if driver.GetTarget() == nil { l = &Logger{ + minLevel: minLevel, infoLogger: log.New(io.Discard, "info: ", log.LstdFlags), warningLogger: log.New(io.Discard, "warning: ", log.LstdFlags), errorLogger: log.New(io.Discard, "error: ", log.LstdFlags), @@ -54,41 +133,103 @@ func NewLogger(driver LogsDriver) *Logger { if !ok { panic("something wrong with the file path") } - logsFile, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644) + var err error + logsFile, err = os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644) if err != nil { panic(err) } - l = &Logger{ - infoLogger: log.New(logsFile, "info: ", log.LstdFlags), - warningLogger: log.New(logsFile, "warning: ", log.LstdFlags), - errorLogger: log.New(logsFile, "error: ", log.LstdFlags), - debugLogger: log.New(logsFile, "debug: ", log.LstdFlags), + + if stdoutEnabled { + // Build each logger with a MultiWriter: the file gets the original plain output, + // stdout gets the output with ANSI-colored prefixes. + infoPlain, infoColored := levelPrefixes(INFO) + debugPlain, debugColored := levelPrefixes(DEBUG) + warnPlain, warnColored := levelPrefixes(WARNING) + errPlain, errColored := levelPrefixes(ERROR) + + l = &Logger{ + minLevel: minLevel, + infoLogger: log.New( + io.MultiWriter(logsFile, &coloredWriter{writer: os.Stdout, plain: infoPlain, colored: infoColored}), + infoPlain, log.LstdFlags, + ), + warningLogger: log.New( + io.MultiWriter(logsFile, &coloredWriter{writer: os.Stdout, plain: warnPlain, colored: warnColored}), + warnPlain, log.LstdFlags, + ), + errorLogger: log.New( + io.MultiWriter(logsFile, &coloredWriter{writer: os.Stdout, plain: errPlain, colored: errColored}), + errPlain, log.LstdFlags, + ), + debugLogger: log.New( + io.MultiWriter(logsFile, &coloredWriter{writer: os.Stdout, plain: debugPlain, colored: debugColored}), + debugPlain, log.LstdFlags, + ), + file: logsFile, + } + } else { + // No stdout: all output goes to file with plain prefixes + l = &Logger{ + minLevel: minLevel, + infoLogger: log.New(logsFile, "info: ", log.LstdFlags), + warningLogger: log.New(logsFile, "warning: ", log.LstdFlags), + errorLogger: log.New(logsFile, "error: ", log.LstdFlags), + debugLogger: log.New(logsFile, "debug: ", log.LstdFlags), + file: logsFile, + } } return l } +// NewLoggerWithLevel creates a new Logger with the given driver and minimum log level. +// Messages below the minimum level will be discarded. Stdout output is disabled by default. +func NewLoggerWithLevel(driver LogsDriver, minLevel Level) *Logger { + stdoutEnabled := os.Getenv("LOG_STDOUT_ENABLE") == "true" + return NewLoggerWithStdout(driver, minLevel, stdoutEnabled) +} + +// SetLevel sets the minimum log level for the logger. +// Messages below this level will be discarded. +func (l *Logger) SetLevel(level Level) { + l.minLevel = level +} + +// GetLevel returns the current minimum log level. +func (l *Logger) GetLevel() Level { + return l.minLevel +} + func ResolveLogger() *Logger { return l } func (l *Logger) Info(msg interface{}) { - l.infoLogger.Println(msg) + if l.minLevel <= INFO { + l.infoLogger.Println(msg) + } } func (l *Logger) Debug(msg interface{}) { - l.debugLogger.Println(msg) + if l.minLevel <= DEBUG { + l.debugLogger.Println(msg) + } } func (l *Logger) Warning(msg interface{}) { - l.warningLogger.Println(msg) + if l.minLevel <= WARNING { + l.warningLogger.Println(msg) + } } func (l *Logger) Error(msg interface{}) { - l.errorLogger.Println(msg) -} - -func CloseLogsFile() { - if logsFile != nil { - defer logsFile.Close() + if l.minLevel <= ERROR { + l.errorLogger.Println(msg) } } + +func (l *Logger) Close() error { + if l.file != nil { + return l.file.Close() + } + return nil +} diff --git a/logger/logger_test.go b/logger/logger_test.go index f82e8a1..46760ca 100644 --- a/logger/logger_test.go +++ b/logger/logger_test.go @@ -61,7 +61,7 @@ func TestInfo(t *testing.T) { t.Error("error testing info") } t.Cleanup(func() { - CloseLogsFile() + l.Close() }) } @@ -84,7 +84,7 @@ func TestWarning(t *testing.T) { t.Error("failed testing warning") } t.Cleanup(func() { - CloseLogsFile() + l.Close() }) } @@ -106,7 +106,7 @@ func TestDebug(t *testing.T) { t.Error("error testing debug") } t.Cleanup(func() { - CloseLogsFile() + l.Close() }) } @@ -128,6 +128,173 @@ func TestError(t *testing.T) { t.Error("failed testing error") } t.Cleanup(func() { - CloseLogsFile() + l.Close() }) } + +func TestLevelFiltering(t *testing.T) { + t.Run("NewLoggerWithLevel_DEBUG", func(t *testing.T) { + path := filepath.Join(t.TempDir(), uuid.NewString()) + l := NewLoggerWithLevel(&LogFileDriver{FilePath: path}, DEBUG) + l.Debug("debug-msg") + l.Info("info-msg") + l.Warning("warn-msg") + l.Error("err-msg") + l.Close() + + b, _ := os.ReadFile(path) + content := string(b) + if !strings.Contains(content, "debug-msg") { + t.Error("expected debug-msg to be logged at DEBUG level") + } + if !strings.Contains(content, "info-msg") { + t.Error("expected info-msg to be logged at DEBUG level") + } + if !strings.Contains(content, "warn-msg") { + t.Error("expected warn-msg to be logged at DEBUG level") + } + if !strings.Contains(content, "err-msg") { + t.Error("expected err-msg to be logged at DEBUG level") + } + }) + + t.Run("NewLoggerWithLevel_INFO", func(t *testing.T) { + path := filepath.Join(t.TempDir(), uuid.NewString()) + l := NewLoggerWithLevel(&LogFileDriver{FilePath: path}, INFO) + l.Debug("debug-msg") + l.Info("info-msg") + l.Warning("warn-msg") + l.Error("err-msg") + l.Close() + + b, _ := os.ReadFile(path) + content := string(b) + if strings.Contains(content, "debug-msg") { + t.Error("debug-msg should NOT be logged at INFO minimum level") + } + if !strings.Contains(content, "info-msg") { + t.Error("expected info-msg to be logged at INFO level") + } + if !strings.Contains(content, "warn-msg") { + t.Error("expected warn-msg to be logged at INFO level") + } + if !strings.Contains(content, "err-msg") { + t.Error("expected err-msg to be logged at INFO level") + } + }) + + t.Run("NewLoggerWithLevel_WARNING", func(t *testing.T) { + path := filepath.Join(t.TempDir(), uuid.NewString()) + l := NewLoggerWithLevel(&LogFileDriver{FilePath: path}, WARNING) + l.Debug("debug-msg") + l.Info("info-msg") + l.Warning("warn-msg") + l.Error("err-msg") + l.Close() + + b, _ := os.ReadFile(path) + content := string(b) + if strings.Contains(content, "debug-msg") { + t.Error("debug-msg should NOT be logged at WARNING minimum level") + } + if strings.Contains(content, "info-msg") { + t.Error("info-msg should NOT be logged at WARNING minimum level") + } + if !strings.Contains(content, "warn-msg") { + t.Error("expected warn-msg to be logged at WARNING level") + } + if !strings.Contains(content, "err-msg") { + t.Error("expected err-msg to be logged at WARNING level") + } + }) + + t.Run("NewLoggerWithLevel_ERROR", func(t *testing.T) { + path := filepath.Join(t.TempDir(), uuid.NewString()) + l := NewLoggerWithLevel(&LogFileDriver{FilePath: path}, ERROR) + l.Debug("debug-msg") + l.Info("info-msg") + l.Warning("warn-msg") + l.Error("err-msg") + l.Close() + + b, _ := os.ReadFile(path) + content := string(b) + if strings.Contains(content, "debug-msg") { + t.Error("debug-msg should NOT be logged at ERROR minimum level") + } + if strings.Contains(content, "info-msg") { + t.Error("info-msg should NOT be logged at ERROR minimum level") + } + if strings.Contains(content, "warn-msg") { + t.Error("warn-msg should NOT be logged at ERROR minimum level") + } + if !strings.Contains(content, "err-msg") { + t.Error("expected err-msg to be logged at ERROR level") + } + }) + + t.Run("SetLevel_dynamically", func(t *testing.T) { + path := filepath.Join(t.TempDir(), uuid.NewString()) + l := NewLogger(&LogFileDriver{FilePath: path}) + + // Default is DEBUG, so debug messages are logged + l.Debug("debug-msg-before") + l.SetLevel(WARNING) + l.Debug("debug-msg-after") + l.Info("info-msg-after") + l.Warning("warn-msg-after") + l.Error("err-msg-after") + l.Close() + + b, _ := os.ReadFile(path) + content := string(b) + if !strings.Contains(content, "debug-msg-before") { + t.Error("expected debug-msg-before to be logged before level change") + } + if strings.Contains(content, "debug-msg-after") { + t.Error("debug-msg-after should NOT be logged after setting level to WARNING") + } + if strings.Contains(content, "info-msg-after") { + t.Error("info-msg-after should NOT be logged after setting level to WARNING") + } + if !strings.Contains(content, "warn-msg-after") { + t.Error("expected warn-msg-after to be logged at WARNING level") + } + if !strings.Contains(content, "err-msg-after") { + t.Error("expected err-msg-after to be logged at WARNING level") + } + }) +} + +func TestLevelString(t *testing.T) { + tests := []struct { + level Level + want string + }{ + {DEBUG, "debug"}, + {INFO, "info"}, + {WARNING, "warning"}, + {ERROR, "error"}, + {Level(99), "unknown"}, + } + for _, tt := range tests { + if got := tt.level.String(); got != tt.want { + t.Errorf("Level(%d).String() = %q, want %q", tt.level, got, tt.want) + } + } +} + +func TestGetLevel(t *testing.T) { + path := filepath.Join(t.TempDir(), uuid.NewString()) + l := NewLoggerWithLevel(&LogFileDriver{FilePath: path}, WARNING) + defer l.Close() + + if l.GetLevel() != WARNING { + t.Errorf("GetLevel() = %d, want %d", l.GetLevel(), WARNING) + } + + l.SetLevel(INFO) + if l.GetLevel() != INFO { + t.Errorf("GetLevel() after SetLevel(INFO) = %d, want %d", l.GetLevel(), INFO) + } +} diff --git a/queue.go b/queue.go new file mode 100644 index 0000000..905a6ed --- /dev/null +++ b/queue.go @@ -0,0 +1,52 @@ +// Copyright (c) 2025 Zeni Kim +// Use of this source code is governed by MIT-style +// license that can be found in the LICENSE file. + +package core + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/hibiken/asynq" +) + +type Asynqtask func(context.Context, *asynq.Task) error + +type Queuemux struct { + themux *asynq.ServeMux +} + +func (q *Queuemux) QueueInit() { + q.themux = asynq.NewServeMux() +} + +func (q *Queuemux) AddWork(pattern string, work Asynqtask) { + q.themux.HandleFunc(pattern, work) +} + +// RunQueueserver starts the queue server with predefined configurations and handles tasks using the assigned ServeMux. +// Configures the queue server with concurrency limits and priority-based queue management. +// Logs and terminates the program if the server fails to run. +func (q *Queuemux) RunQueueserver() { + + redisAddr := fmt.Sprintf("%v:%v", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PORT")) + + srv := asynq.NewServer( + asynq.RedisClientOpt{Addr: redisAddr}, + asynq.Config{Concurrency: 10, + // Optionally specify multiple queues with different priority. + Queues: map[string]int{ + "critical": 6, + "default": 3, + "low": 1, + }, + }, + ) + + if err := srv.Run(q.themux); err != nil { + log.Fatal(err) + } +} diff --git a/response.go b/response.go index 7c03b15..d6202c7 100644 --- a/response.go +++ b/response.go @@ -11,6 +11,7 @@ import ( "net/http" ) +// Response represents an HTTP response to be sent to the client, including headers, body, status code, and metadata. type Response struct { headers []header body []byte @@ -22,12 +23,34 @@ type Response struct { HttpResponseWriter http.ResponseWriter } +// header represents a single HTTP header with a key-value pair. type header struct { key string val string } -// TODO add doc +// writes the contents of a buffer to the HTTP response with specified file name and type if not terminated. +func (rs *Response) BufferFile(name string, filetype string, b bytes.Buffer) *Response { + + if rs.isTerminated == false { + rs.HttpResponseWriter.Header().Add("Content-Type", filetype) + rs.HttpResponseWriter.Header().Add("Content-Disposition", "attachment; filename="+name) + b.WriteTo(rs.HttpResponseWriter) + } + return rs +} + +// writes the contents of a buffer to the HTTP response with specified file name and type if not terminated. +func (rs *Response) BufferInline(name string, filetype string, b bytes.Buffer) *Response { + + if rs.isTerminated == false { + rs.HttpResponseWriter.Header().Add("Content-Type", filetype) + b.WriteTo(rs.HttpResponseWriter) + } + return rs +} + +// sets the response's content type to HTML and assigns the provided body as the response body if not terminated. func (rs *Response) Any(body any) *Response { if rs.isTerminated == false { rs.contentType = CONTENT_TYPE_HTML @@ -37,7 +60,7 @@ func (rs *Response) Any(body any) *Response { return rs } -// TODO add doc +// sets the response's content type to JSON and assigns the provided string as the body if the response is not terminated. func (rs *Response) Json(body string) *Response { if rs.isTerminated == false { rs.contentType = CONTENT_TYPE_JSON @@ -46,7 +69,7 @@ func (rs *Response) Json(body string) *Response { return rs } -// TODO add doc +// sets the response's content type to plain text and assigns the provided string as the body if not terminated. func (rs *Response) Text(body string) *Response { if rs.isTerminated == false { rs.contentType = CONTENT_TYPE_TEXT @@ -55,7 +78,7 @@ func (rs *Response) Text(body string) *Response { return rs } -// TODO add doc +// sets the response's content type to HTML and assigns the provided string as the body if the response is not terminated. func (rs *Response) HTML(body string) *Response { if rs.isTerminated == false { rs.contentType = CONTENT_TYPE_HTML @@ -64,7 +87,7 @@ func (rs *Response) HTML(body string) *Response { return rs } -// TODO add doc +// renders the specified template with the provided data and writes the result to the HTTP response if not terminated. func (rs *Response) Template(name string, data interface{}) *Response { var buffer bytes.Buffer if rs.isTerminated == false { @@ -78,7 +101,7 @@ func (rs *Response) Template(name string, data interface{}) *Response { return rs } -// TODO add doc +// sets the response status code if the response is not yet terminated. Returns the updated Response object. func (rs *Response) SetStatusCode(code int) *Response { if rs.isTerminated == false { rs.statusCode = code @@ -87,7 +110,7 @@ func (rs *Response) SetStatusCode(code int) *Response { return rs } -// TODO add doc +// sets a custom content type for the response if it is not terminated. Returns the updated Response object. func (rs *Response) SetContentType(c string) *Response { if rs.isTerminated == false { rs.overrideContentType = c @@ -96,7 +119,7 @@ func (rs *Response) SetContentType(c string) *Response { return rs } -// TODO add doc +// adds or updates a header to the response if it is not terminated. Returns the updated Response object. func (rs *Response) SetHeader(key string, val string) *Response { if rs.isTerminated == false { h := header{ @@ -108,10 +131,12 @@ func (rs *Response) SetHeader(key string, val string) *Response { return rs } +// terminates the response processing, preventing any further modifications or actions. func (rs *Response) ForceSendResponse() { rs.isTerminated = true } +// updates the redirect URL for the response and returns the modified Response. Validates the URL before setting it. func (rs *Response) Redirect(url string) *Response { validator := resolveValidator() v := validator.Validate(map[string]interface{}{ @@ -131,6 +156,7 @@ func (rs *Response) Redirect(url string) *Response { return rs } +// converts various primitive data types to their string representation or triggers a panic for unsupported types. func (rs *Response) castBasicVarsToString(data interface{}) string { switch dataType := data.(type) { case string: @@ -188,6 +214,7 @@ func (rs *Response) castBasicVarsToString(data interface{}) string { } } +// reinitializes the Response object to its default state, clearing its body, headers, and resetting other properties. func (rs *Response) reset() { rs.body = nil rs.statusCode = http.StatusOK diff --git a/router.go b/router.go index 24141b4..163f22a 100644 --- a/router.go +++ b/router.go @@ -5,6 +5,7 @@ package core +// Route defines an HTTP route with a method, path, controller function, and optional hooks for customization. type Route struct { Method string Path string @@ -12,12 +13,15 @@ type Route struct { Hooks []Hook } +// Router represents a structure for storing and managing routes in the application. type Router struct { Routes []Route } +// router is a global instance of the Router struct used to manage and resolve application routes. var router *Router +// NewRouter initializes and returns a new Router instance with an empty slice of routes. func NewRouter() *Router { router = &Router{ []Route{}, @@ -25,10 +29,12 @@ func NewRouter() *Router { return router } +// ResolveRouter returns the singleton instance of the Router. It initializes and manages HTTP routes configuration. func ResolveRouter() *Router { return router } +// Get registers a GET route with the specified path, controller, and optional hooks, returning the updated Router. func (r *Router) Get(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: GET, @@ -39,6 +45,7 @@ func (r *Router) Get(path string, controller Controller, hooks ...Hook) *Router return r } +// Post registers a route with the HTTP POST method, associating it with the given path, controller, and optional hooks. func (r *Router) Post(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: POST, @@ -49,6 +56,7 @@ func (r *Router) Post(path string, controller Controller, hooks ...Hook) *Router return r } +// Delete registers a DELETE HTTP method route with the specified path, controller, and optional hooks. func (r *Router) Delete(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: DELETE, @@ -59,6 +67,7 @@ func (r *Router) Delete(path string, controller Controller, hooks ...Hook) *Rout return r } +// Patch registers a new route with the HTTP PATCH method, a specified path, a controller, and optional hooks. func (r *Router) Patch(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: PATCH, @@ -69,6 +78,7 @@ func (r *Router) Patch(path string, controller Controller, hooks ...Hook) *Route return r } +// Put registers a new route with the HTTP PUT method, associating it to the given path, controller, and optional hooks. func (r *Router) Put(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: PUT, @@ -79,6 +89,7 @@ func (r *Router) Put(path string, controller Controller, hooks ...Hook) *Router return r } +// Options registers a new route with the OPTIONS HTTP method, a specified path, controller, and optional hooks. func (r *Router) Options(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: OPTIONS, @@ -89,6 +100,7 @@ func (r *Router) Options(path string, controller Controller, hooks ...Hook) *Rou return r } +// Head registers a route with the HTTP HEAD method, associates it with a path, controller, and optional hooks. func (r *Router) Head(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: HEAD, @@ -99,6 +111,7 @@ func (r *Router) Head(path string, controller Controller, hooks ...Hook) *Router return r } +// GetRoutes returns a slice of Route objects currently registered within the Router. func (r *Router) GetRoutes() []Route { return r.Routes } diff --git a/template/components/content_dropdown.go b/template/components/content_dropdown.go index 78c41c7..65eb21f 100644 --- a/template/components/content_dropdown.go +++ b/template/components/content_dropdown.go @@ -1,6 +1,7 @@ package components type ContentDropdown struct { + ID string Label string TypeClass string // type primary, secondary, success, danger, warning, info, light, dark, link, outline-primary IsDisabled bool diff --git a/template/components/content_list.go b/template/components/content_list.go index 34bfb49..62927e6 100644 --- a/template/components/content_list.go +++ b/template/components/content_list.go @@ -1,10 +1,12 @@ package components type ContentList struct { + ID string Items []ContentListItem } type ContentListItem struct { + ID string Text string Description string EndElement string diff --git a/template/components/content_list.html b/template/components/content_list.html index 31af60b..351bcad 100644 --- a/template/components/content_list.html +++ b/template/components/content_list.html @@ -1,8 +1,10 @@ {{define "content_list"}} -
    +
      {{ range .Items}} -
    • {{.Text}}

      {{.EndElement}}
      {{.Description}}
    • diff --git a/template/components/content_pagination.go b/template/components/content_pagination.go new file mode 100644 index 0000000..87434a2 --- /dev/null +++ b/template/components/content_pagination.go @@ -0,0 +1,9 @@ +package components + +type ContentPagination struct { + PageStartRecord int + PageEndRecord int + TotalRecords int + PrevLink string + NextLink string +} diff --git a/template/components/content_pagination.html b/template/components/content_pagination.html new file mode 100644 index 0000000..a51e09d --- /dev/null +++ b/template/components/content_pagination.html @@ -0,0 +1,10 @@ +{{define "content_pagination"}} +
      +
        +
      • {{.PageStartRecord}} - {{.PageEndRecord}} of {{.TotalRecords}}
      • +
      •  
      • +
      • «
      • +
      • »
      • +
      +
      +{{end}} \ No newline at end of file diff --git a/template/components/content_table.go b/template/components/content_table.go index 1cb7024..5c6a21b 100644 --- a/template/components/content_table.go +++ b/template/components/content_table.go @@ -10,11 +10,12 @@ type ContentTable struct { type ContentTableTH struct { ID string - ValueType string // -> default string, href, badge + ValueType string // -> default string, href, badge, list, checkbox Value string } type ContentTableTD struct { - ID string - Value interface{} // string or component struct according ValueType + ID string + Value interface{} // string or component struct according ValueType + ValueClass string } diff --git a/template/components/content_table.html b/template/components/content_table.html index 2bf559d..36f9b8b 100644 --- a/template/components/content_table.html +++ b/template/components/content_table.html @@ -7,12 +7,18 @@ {{- range .AllTD}} - {{range $index, $item := .}} + {{range $index, $item := .}} {{ with $x := index $.AllTH $index }} {{ if eq $x.ValueType "href"}} {{template "content_href" $item.Value}} {{ else if eq $x.ValueType "badge"}} {{template "content_badge" $item.Value}} + {{ else if eq $x.ValueType "list"}} + {{template "content_list" $item.Value}} + {{ else if eq $x.ValueType "checkbox"}} + {{template "form_checkbox" $item.Value}} + {{ else if eq $x.ValueType "image"}} + {{ else }} {{ $item.Value }} {{end}} diff --git a/template/components/form_button.go b/template/components/form_button.go index 658306e..4b451bf 100644 --- a/template/components/form_button.go +++ b/template/components/form_button.go @@ -1,6 +1,8 @@ package components type FormButton struct { + ID string + Value string Text string Icon string IsSubmit bool diff --git a/template/components/form_button.html b/template/components/form_button.html index 7594613..b58a9ed 100644 --- a/template/components/form_button.html +++ b/template/components/form_button.html @@ -1,5 +1,5 @@ {{define "form_button"}} - diff --git a/template/components/form_checkbox.html b/template/components/form_checkbox.html index 9a8d845..992cff0 100644 --- a/template/components/form_checkbox.html +++ b/template/components/form_checkbox.html @@ -1,6 +1,6 @@ {{define "form_checkbox"}}
      - + {{ if .Label }}{{end}} {{range $options := .AllCheckbox}}
      diff --git a/template/components/form_input.go b/template/components/form_input.go index e27910f..0ee8150 100644 --- a/template/components/form_input.go +++ b/template/components/form_input.go @@ -1,13 +1,20 @@ package components type FormInput struct { - ID string - Label string - Type string - Placeholder string - Value string - Hint string - Error string - IsDisabled bool - IsRequired bool + ID string + Label string + Type string + Placeholder string + Value string + Hint string + Error string + IsDisabled bool + Autocomplete bool + IsRequired bool + CustomAtt []CustomAtt +} + +type CustomAtt struct { + AttName string + AttValue string } diff --git a/template/components/form_input.html b/template/components/form_input.html index 8159896..adf33e8 100644 --- a/template/components/form_input.html +++ b/template/components/form_input.html @@ -8,9 +8,17 @@ {{if eq .IsRequired true}} required {{end}} + {{if eq .Autocomplete false}} + autocomplete="off" + {{end}} {{if ne .Value ""}} value="{{.Value}}" {{end}} + {{if .CustomAtt }} + {{range $options := .CustomAtt}} + {{$options.AttName}}="{{$options.AttValue}}" + {{end}} + {{end}} aria-describedby="{{.ID}}Help"> {{if ne .Hint ""}}{{.Hint}}{{end}} {{if ne .Error ""}}
      {{.Error}}
      {{end}} diff --git a/template/components/form_select.go b/template/components/form_select.go index db94fe3..ea10ea5 100644 --- a/template/components/form_select.go +++ b/template/components/form_select.go @@ -5,6 +5,7 @@ type FormSelect struct { SelectedOption FormSelectOption Label string AllOptions []FormSelectOption + IsMultiple bool } type FormSelectOption struct { diff --git a/template/components/form_select.html b/template/components/form_select.html index 6317e6b..eb222e5 100644 --- a/template/components/form_select.html +++ b/template/components/form_select.html @@ -1,7 +1,7 @@ {{define "form_select"}}
      - {{range $options := .AllOptions}} {{end}} diff --git a/template/components/page_nav.go b/template/components/page_nav.go index 862d1c8..671e79a 100644 --- a/template/components/page_nav.go +++ b/template/components/page_nav.go @@ -10,6 +10,7 @@ type PageNav struct { type PageNavItem struct { Text string Link string + ID string IsDisabled bool IsActive bool ChildItems []PageNavItem diff --git a/template/components/page_nav.html b/template/components/page_nav.html index 08faaf4..354dd55 100644 --- a/template/components/page_nav.html +++ b/template/components/page_nav.html @@ -1,11 +1,16 @@ {{define "page_nav"}}