Merge pull request 'develop' (#20) from jacs/core:develop into develop
Reviewed-on: #20
This commit is contained in:
commit
530a1171e6
9 changed files with 135 additions and 24 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -1,2 +1,3 @@
|
||||||
tmp
|
tmp
|
||||||
.DS_STore
|
.DS_STore
|
||||||
|
.idea
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
# GoCondor Core
|
# Goffee Core
|
||||||
  [](https://coveralls.io/github/gocondor/core?branch=main&cache=false) [](https://godoc.org/github.com/gocondor/core) [](https://goreportcard.com/report/github.com/gocondor/core)
|
|
||||||
|
|
||||||
The core packages of GoCondor framework
|
The core packages of Goffee framework
|
||||||
|
|
8
cache.go
8
cache.go
|
@ -16,6 +16,9 @@ type Cache struct {
|
||||||
redis *redis.Client
|
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 {
|
func NewCache(cacheConfig CacheConfig) *Cache {
|
||||||
ctx = context.Background()
|
ctx = context.Background()
|
||||||
dbStr := os.Getenv("REDIS_DB")
|
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 {
|
func (c *Cache) Set(key string, value string) error {
|
||||||
err := c.redis.Set(ctx, key, value, 0).Err()
|
err := c.redis.Set(ctx, key, value, 0).Err()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -48,6 +52,8 @@ func (c *Cache) Set(key string, value string) error {
|
||||||
return nil
|
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 {
|
func (c *Cache) SetWithExpiration(key string, value string, expiration time.Duration) error {
|
||||||
err := c.redis.Set(ctx, key, value, expiration).Err()
|
err := c.redis.Set(ctx, key, value, expiration).Err()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -56,6 +62,7 @@ func (c *Cache) SetWithExpiration(key string, value string, expiration time.Dura
|
||||||
return nil
|
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) {
|
func (c *Cache) Get(key string) (string, error) {
|
||||||
result, err := c.redis.Get(ctx, key).Result()
|
result, err := c.redis.Get(ctx, key).Result()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -64,6 +71,7 @@ func (c *Cache) Get(key string) (string, error) {
|
||||||
return result, nil
|
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 {
|
func (c *Cache) Delete(key string) error {
|
||||||
err := c.redis.Del(ctx, key).Err()
|
err := c.redis.Del(ctx, key).Err()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
29
context.go
29
context.go
|
@ -121,34 +121,43 @@ func (c *Context) GetQueueClient() *asynq.Client {
|
||||||
return client
|
return client
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) GetUploadedFile(name string) *UploadedFileInfo {
|
func (c *Context) GetUploadedFile(name string) (*UploadedFileInfo, error) {
|
||||||
file, fileHeader, err := c.Request.httpRequest.FormFile(name)
|
file, fileHeader, err := c.Request.httpRequest.FormFile(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(fmt.Sprintf("error with file,[%v]", err.Error()))
|
return nil, fmt.Errorf("error retrieving file: %v", err)
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
|
||||||
|
// Extract the file extension
|
||||||
ext := strings.TrimPrefix(path.Ext(fileHeader.Filename), ".")
|
ext := strings.TrimPrefix(path.Ext(fileHeader.Filename), ".")
|
||||||
tmpFilePath := filepath.Join(os.TempDir(), fileHeader.Filename)
|
tmpFilePath := filepath.Join(os.TempDir(), fileHeader.Filename)
|
||||||
tmpFile, err := os.Create(tmpFilePath)
|
tmpFile, err := os.Create(tmpFilePath)
|
||||||
if err != nil {
|
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)
|
buff := make([]byte, 100)
|
||||||
for {
|
for {
|
||||||
n, err := file.Read(buff)
|
n, err := file.Read(buff)
|
||||||
if err != nil && err != io.EOF {
|
if err != nil && err != io.EOF {
|
||||||
panic("error with uploaded file")
|
return nil, fmt.Errorf("error reading uploaded file: %v", err)
|
||||||
}
|
}
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
break
|
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)
|
tmpFileInfo, err := os.Stat(tmpFilePath)
|
||||||
if err != nil {
|
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{
|
uploadedFileInfo := &UploadedFileInfo{
|
||||||
FullPath: tmpFilePath,
|
FullPath: tmpFilePath,
|
||||||
Name: fileHeader.Filename,
|
Name: fileHeader.Filename,
|
||||||
|
@ -156,7 +165,7 @@ func (c *Context) GetUploadedFile(name string) *UploadedFileInfo {
|
||||||
Extension: ext,
|
Extension: ext,
|
||||||
Size: int(tmpFileInfo.Size()),
|
Size: int(tmpFileInfo.Size()),
|
||||||
}
|
}
|
||||||
return uploadedFileInfo
|
return uploadedFileInfo, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error {
|
func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error {
|
||||||
|
@ -185,7 +194,7 @@ func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error {
|
||||||
for {
|
for {
|
||||||
n, err := srcFile.Read(buff)
|
n, err := srcFile.Read(buff)
|
||||||
if err != nil && err != io.EOF {
|
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 {
|
if n == 0 {
|
||||||
break
|
break
|
||||||
|
@ -229,7 +238,7 @@ func (c *Context) CopyFile(sourceFilePath string, destFolderPath string) error {
|
||||||
for {
|
for {
|
||||||
n, err := srcFile.Read(buff)
|
n, err := srcFile.Read(buff)
|
||||||
if err != nil && err != io.EOF {
|
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 {
|
if n == 0 {
|
||||||
break
|
break
|
||||||
|
|
17
cookies.go
17
cookies.go
|
@ -21,19 +21,24 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ErrValueTooLong indicates that the cookie value exceeds the allowed length limit.
|
||||||
|
// ErrInvalidValue signifies that the cookie value is in an invalid format.
|
||||||
var (
|
var (
|
||||||
ErrValueTooLong = errors.New("cookie value too long")
|
ErrValueTooLong = errors.New("cookie value too long")
|
||||||
ErrInvalidValue = errors.New("invalid cookie value")
|
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 {
|
type UserCookie struct {
|
||||||
Email string
|
Email string
|
||||||
Token string
|
Token string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// secretcookie is a global variable used to store the decoded secret key for encrypting and decrypting cookies.
|
||||||
var secretcookie []byte
|
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) {
|
func GetCookie(r *http.Request) (UserCookie, error) {
|
||||||
|
|
||||||
var err 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 {
|
func SetCookie(w http.ResponseWriter, email string, token string) error {
|
||||||
// Initialize a User struct containing the data that we want to store in the
|
// Initialize a User struct containing the data that we want to store in the
|
||||||
// cookie.
|
// cookie.
|
||||||
|
@ -138,6 +144,8 @@ func SetCookie(w http.ResponseWriter, email string, token string) error {
|
||||||
return nil
|
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 {
|
func CookieWrite(w http.ResponseWriter, cookie http.Cookie) error {
|
||||||
// Encode the cookie value using base64.
|
// Encode the cookie value using base64.
|
||||||
cookie.Value = base64.URLEncoding.EncodeToString([]byte(cookie.Value))
|
cookie.Value = base64.URLEncoding.EncodeToString([]byte(cookie.Value))
|
||||||
|
@ -154,6 +162,8 @@ func CookieWrite(w http.ResponseWriter, cookie http.Cookie) error {
|
||||||
return nil
|
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) {
|
func CookieRead(r *http.Request, name string) (string, error) {
|
||||||
// Read the cookie as normal.
|
// Read the cookie as normal.
|
||||||
cookie, err := r.Cookie(name)
|
cookie, err := r.Cookie(name)
|
||||||
|
@ -173,6 +183,9 @@ func CookieRead(r *http.Request, name string) (string, error) {
|
||||||
return string(value), nil
|
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 {
|
func CookieWriteEncrypted(w http.ResponseWriter, cookie http.Cookie, secretKey []byte) error {
|
||||||
// Create a new AES cipher block from the secret key.
|
// Create a new AES cipher block from the secret key.
|
||||||
block, err := aes.NewCipher(secretKey)
|
block, err := aes.NewCipher(secretKey)
|
||||||
|
@ -213,6 +226,8 @@ func CookieWriteEncrypted(w http.ResponseWriter, cookie http.Cookie, secretKey [
|
||||||
return CookieWrite(w, cookie)
|
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) {
|
func CookieReadEncrypted(r *http.Request, name string, secretKey []byte) (string, error) {
|
||||||
// Read the encrypted value from the cookie as normal.
|
// Read the encrypted value from the cookie as normal.
|
||||||
encryptedValue, err := CookieRead(r, name)
|
encryptedValue, err := CookieRead(r, name)
|
||||||
|
|
57
core.go
57
core.go
|
@ -39,13 +39,17 @@ var basePath string
|
||||||
var runMode string
|
var runMode string
|
||||||
var disableEvents bool = false
|
var disableEvents bool = false
|
||||||
|
|
||||||
|
// components_resources holds embedded file system data, typically for templates or other embedded resources.
|
||||||
|
//
|
||||||
//go:embed all:template
|
//go:embed all:template
|
||||||
var components_resources embed.FS
|
var components_resources embed.FS
|
||||||
|
|
||||||
|
// configContainer is a configuration structure that holds request-specific configurations for the application.
|
||||||
type configContainer struct {
|
type configContainer struct {
|
||||||
Request RequestConfig
|
Request RequestConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// App is a struct representing the main application container and its core components.
|
||||||
type App struct {
|
type App struct {
|
||||||
t int // for tracking hooks
|
t int // for tracking hooks
|
||||||
chain *chain
|
chain *chain
|
||||||
|
@ -53,8 +57,10 @@ type App struct {
|
||||||
Config *configContainer
|
Config *configContainer
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// app is a global instance of the App structure used to manage application configuration and lifecycle.
|
||||||
var app *App
|
var app *App
|
||||||
|
|
||||||
|
// New initializes and returns a new instance of the App structure with default configurations and chain.
|
||||||
func New() *App {
|
func New() *App {
|
||||||
app = &App{
|
app = &App{
|
||||||
chain: &chain{},
|
chain: &chain{},
|
||||||
|
@ -66,24 +72,29 @@ func New() *App {
|
||||||
return app
|
return app
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ResolveApp returns the global instance of the App, providing access to its methods and configuration components.
|
||||||
func ResolveApp() *App {
|
func ResolveApp() *App {
|
||||||
return app
|
return app
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetLogsDriver sets the logging driver to be used by the application.
|
||||||
func (app *App) SetLogsDriver(d logger.LogsDriver) {
|
func (app *App) SetLogsDriver(d logger.LogsDriver) {
|
||||||
logsDriver = &d
|
logsDriver = &d
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bootstrap initializes the application by setting up the logger, router, and events manager.
|
||||||
func (app *App) Bootstrap() {
|
func (app *App) Bootstrap() {
|
||||||
loggr = logger.NewLogger(*logsDriver)
|
loggr = logger.NewLogger(*logsDriver)
|
||||||
NewRouter()
|
NewRouter()
|
||||||
NewEventsManager()
|
NewEventsManager()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterTemplates initializes the application template system by embedding provided templates for rendering views.
|
||||||
func (app *App) RegisterTemplates(templates_resources embed.FS) {
|
func (app *App) RegisterTemplates(templates_resources embed.FS) {
|
||||||
NewTemplates(components_resources, templates_resources)
|
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) {
|
func (app *App) Run(router *httprouter.Router) {
|
||||||
portNumber := os.Getenv("App_HTTP_PORT")
|
portNumber := os.Getenv("App_HTTP_PORT")
|
||||||
if portNumber == "" {
|
if portNumber == "" {
|
||||||
|
@ -156,6 +167,9 @@ func (app *App) Run(router *httprouter.Router) {
|
||||||
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", portNumber), 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 {
|
func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httprouter.Router {
|
||||||
router.PanicHandler = panicHandler
|
router.PanicHandler = panicHandler
|
||||||
router.NotFound = notFoundHandler{}
|
router.NotFound = notFoundHandler{}
|
||||||
|
@ -194,6 +208,7 @@ func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httpr
|
||||||
return router
|
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 {
|
func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Handle {
|
||||||
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
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{}
|
type notFoundHandler struct{}
|
||||||
|
|
||||||
|
// methodNotAllowed is a type that implements http.Handler to handle HTTP 405 Method Not Allowed errors.
|
||||||
type methodNotAllowed struct{}
|
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) {
|
func (n notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusNotFound)
|
w.WriteHeader(http.StatusNotFound)
|
||||||
res := "{\"message\": \"Not Found\"}"
|
res := "{\"message\": \"Not Found\"}"
|
||||||
|
@ -272,6 +291,7 @@ func (n notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte(res))
|
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) {
|
func (n methodNotAllowed) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||||
res := "{\"message\": \"Method not allowed\"}"
|
res := "{\"message\": \"Method not allowed\"}"
|
||||||
|
@ -281,6 +301,7 @@ func (n methodNotAllowed) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte(res))
|
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{}) {
|
var panicHandler = func(w http.ResponseWriter, r *http.Request, e interface{}) {
|
||||||
isDebugModeStr := os.Getenv("APP_DEBUG_MODE")
|
isDebugModeStr := os.Getenv("APP_DEBUG_MODE")
|
||||||
isDebugMode, err := strconv.ParseBool(isDebugModeStr)
|
isDebugMode, err := strconv.ParseBool(isDebugModeStr)
|
||||||
|
@ -315,10 +336,12 @@ var panicHandler = func(w http.ResponseWriter, r *http.Request, e interface{}) {
|
||||||
w.Write([]byte(res))
|
w.Write([]byte(res))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UseHook registers a Hook middleware function by attaching it to the global Hooks instance.
|
||||||
func UseHook(mw Hook) {
|
func UseHook(mw Hook) {
|
||||||
ResolveHooks().Attach(mw)
|
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) {
|
func (app *App) Next(c *Context) {
|
||||||
app.t = app.t + 1
|
app.t = app.t + 1
|
||||||
n := app.chain.getByIndex(app.t)
|
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 {
|
type chain struct {
|
||||||
nodes []interface{}
|
nodes []interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// reset clears all nodes in the chain, resetting it to an empty state.
|
||||||
func (cn *chain) reset() {
|
func (cn *chain) reset() {
|
||||||
cn.nodes = []interface{}{}
|
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{} {
|
func (c *chain) getByIndex(i int) interface{} {
|
||||||
for k := range c.nodes {
|
for k := range c.nodes {
|
||||||
if k == i {
|
if k == i {
|
||||||
|
@ -353,6 +379,7 @@ func (c *chain) getByIndex(i int) interface{} {
|
||||||
return nil
|
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{}) {
|
func (app *App) prepareChain(hs []interface{}) {
|
||||||
mw := app.hooks.GetHooks()
|
mw := app.hooks.GetHooks()
|
||||||
for _, v := range mw {
|
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) {
|
func (cn *chain) execute(ctx *Context) {
|
||||||
i := cn.getByIndex(0)
|
i := cn.getByIndex(0)
|
||||||
if i != nil {
|
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{} {
|
func (app *App) combHandlers(h Controller, mw []Hook) []interface{} {
|
||||||
var rev []interface{}
|
var rev []interface{}
|
||||||
for _, k := range mw {
|
for _, k := range mw {
|
||||||
|
@ -387,6 +416,8 @@ func (app *App) combHandlers(h Controller, mw []Hook) []interface{} {
|
||||||
return rev
|
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 {
|
func getGormFunc() func() *gorm.DB {
|
||||||
f := func() *gorm.DB {
|
f := func() *gorm.DB {
|
||||||
if !gormC.EnableGorm {
|
if !gormC.EnableGorm {
|
||||||
|
@ -397,6 +428,9 @@ func getGormFunc() func() *gorm.DB {
|
||||||
return f
|
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 {
|
func NewGorm() *gorm.DB {
|
||||||
var err error
|
var err error
|
||||||
switch os.Getenv("DB_DRIVER") {
|
switch os.Getenv("DB_DRIVER") {
|
||||||
|
@ -421,6 +455,7 @@ func NewGorm() *gorm.DB {
|
||||||
return 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 {
|
func ResolveGorm() *gorm.DB {
|
||||||
if db != nil {
|
if db != nil {
|
||||||
return db
|
return db
|
||||||
|
@ -429,6 +464,8 @@ func ResolveGorm() *gorm.DB {
|
||||||
return 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 {
|
func resolveCache() func() *Cache {
|
||||||
f := func() *Cache {
|
f := func() *Cache {
|
||||||
if !cacheC.EnableCache {
|
if !cacheC.EnableCache {
|
||||||
|
@ -439,6 +476,8 @@ func resolveCache() func() *Cache {
|
||||||
return f
|
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) {
|
func postgresConnect() (*gorm.DB, error) {
|
||||||
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=%v TimeZone=%v",
|
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=%v TimeZone=%v",
|
||||||
os.Getenv("POSTGRES_HOST"),
|
os.Getenv("POSTGRES_HOST"),
|
||||||
|
@ -452,6 +491,8 @@ func postgresConnect() (*gorm.DB, error) {
|
||||||
return gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
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) {
|
func mysqlConnect() (*gorm.DB, error) {
|
||||||
dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v&parseTime=True&loc=Local",
|
dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v&parseTime=True&loc=Local",
|
||||||
os.Getenv("MYSQL_USERNAME"),
|
os.Getenv("MYSQL_USERNAME"),
|
||||||
|
@ -471,6 +512,9 @@ func mysqlConnect() (*gorm.DB, error) {
|
||||||
}), &gorm.Config{})
|
}), &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 {
|
func getJWT() func() *JWT {
|
||||||
f := func() *JWT {
|
f := func() *JWT {
|
||||||
secret := os.Getenv("JWT_SECRET")
|
secret := os.Getenv("JWT_SECRET")
|
||||||
|
@ -494,6 +538,7 @@ func getJWT() func() *JWT {
|
||||||
return f
|
return f
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getValidator returns a closure that instantiates and provides a new instance of Validator.
|
||||||
func getValidator() func() *Validator {
|
func getValidator() func() *Validator {
|
||||||
f := func() *Validator {
|
f := func() *Validator {
|
||||||
return &Validator{}
|
return &Validator{}
|
||||||
|
@ -501,6 +546,7 @@ func getValidator() func() *Validator {
|
||||||
return f
|
return f
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resloveHashing returns a function that initializes and provides a pointer to a new instance of the Hashing struct.
|
||||||
func resloveHashing() func() *Hashing {
|
func resloveHashing() func() *Hashing {
|
||||||
f := func() *Hashing {
|
f := func() *Hashing {
|
||||||
return &Hashing{}
|
return &Hashing{}
|
||||||
|
@ -508,6 +554,7 @@ func resloveHashing() func() *Hashing {
|
||||||
return f
|
return f
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveMailer initializes and returns a function that provides a singleton Mailer instance based on the configured driver.
|
||||||
func resolveMailer() func() *Mailer {
|
func resolveMailer() func() *Mailer {
|
||||||
f := func() *Mailer {
|
f := func() *Mailer {
|
||||||
if mailer != nil {
|
if mailer != nil {
|
||||||
|
@ -536,6 +583,7 @@ func resolveMailer() func() *Mailer {
|
||||||
return f
|
return f
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveEventsManager creates and returns a function that resolves the singleton instance of EventsManager.
|
||||||
func resolveEventsManager() func() *EventsManager {
|
func resolveEventsManager() func() *EventsManager {
|
||||||
f := func() *EventsManager {
|
f := func() *EventsManager {
|
||||||
return ResolveEventsManager()
|
return ResolveEventsManager()
|
||||||
|
@ -543,6 +591,7 @@ func resolveEventsManager() func() *EventsManager {
|
||||||
return f
|
return f
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveLogger returns a function that provides access to the initialized logger instance when invoked.
|
||||||
func resolveLogger() func() *logger.Logger {
|
func resolveLogger() func() *logger.Logger {
|
||||||
f := func() *logger.Logger {
|
f := func() *logger.Logger {
|
||||||
return loggr
|
return loggr
|
||||||
|
@ -550,6 +599,7 @@ func resolveLogger() func() *logger.Logger {
|
||||||
return f
|
return f
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MakeDirs creates the specified directories under the base path with the provided permissions (0766).
|
||||||
func (app *App) MakeDirs(dirs ...string) {
|
func (app *App) MakeDirs(dirs ...string) {
|
||||||
o := syscall.Umask(0)
|
o := syscall.Umask(0)
|
||||||
defer syscall.Umask(o)
|
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) {
|
func (app *App) SetRequestConfig(r RequestConfig) {
|
||||||
requestC = r
|
requestC = r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetGormConfig sets the GormConfig for the application, overriding the current configuration with the provided value.
|
||||||
func (app *App) SetGormConfig(g GormConfig) {
|
func (app *App) SetGormConfig(g GormConfig) {
|
||||||
gormC = g
|
gormC = g
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetCacheConfig sets the cache configuration for the application using the provided CacheConfig parameter.
|
||||||
func (app *App) SetCacheConfig(c CacheConfig) {
|
func (app *App) SetCacheConfig(c CacheConfig) {
|
||||||
cacheC = c
|
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) {
|
func (app *App) SetBasePath(path string) {
|
||||||
basePath = path
|
basePath = path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetRunMode sets the application run mode to the specified value.
|
||||||
func (app *App) SetRunMode(runmode string) {
|
func (app *App) SetRunMode(runmode string) {
|
||||||
runMode = runmode
|
runMode = runmode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DisableEvents sets the global variable `disableEvents` to true, disabling the handling or triggering of events.
|
||||||
func DisableEvents() {
|
func DisableEvents() {
|
||||||
disableEvents = true
|
disableEvents = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EnableEvents sets the global variable `disableEvents` to false, effectively enabling event handling.
|
||||||
func EnableEvents() {
|
func EnableEvents() {
|
||||||
disableEvents = false
|
disableEvents = false
|
||||||
}
|
}
|
||||||
|
|
3
queue.go
3
queue.go
|
@ -27,6 +27,9 @@ func (q *Queuemux) AddWork(pattern string, work Asynqtask) {
|
||||||
q.themux.HandleFunc(pattern, work)
|
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() {
|
func (q *Queuemux) RunQueueserver() {
|
||||||
|
|
||||||
redisAddr := fmt.Sprintf("%v:%v", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PORT"))
|
redisAddr := fmt.Sprintf("%v:%v", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PORT"))
|
||||||
|
|
24
response.go
24
response.go
|
@ -11,6 +11,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Response represents an HTTP response to be sent to the client, including headers, body, status code, and metadata.
|
||||||
type Response struct {
|
type Response struct {
|
||||||
headers []header
|
headers []header
|
||||||
body []byte
|
body []byte
|
||||||
|
@ -22,12 +23,13 @@ type Response struct {
|
||||||
HttpResponseWriter http.ResponseWriter
|
HttpResponseWriter http.ResponseWriter
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// header represents a single HTTP header with a key-value pair.
|
||||||
type header struct {
|
type header struct {
|
||||||
key string
|
key string
|
||||||
val 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 {
|
func (rs *Response) BufferFile(name string, filetype string, b bytes.Buffer) *Response {
|
||||||
|
|
||||||
if rs.isTerminated == false {
|
if rs.isTerminated == false {
|
||||||
|
@ -38,7 +40,7 @@ func (rs *Response) BufferFile(name string, filetype string, b bytes.Buffer) *Re
|
||||||
return rs
|
return rs
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO add doc
|
// 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 {
|
func (rs *Response) Any(body any) *Response {
|
||||||
if rs.isTerminated == false {
|
if rs.isTerminated == false {
|
||||||
rs.contentType = CONTENT_TYPE_HTML
|
rs.contentType = CONTENT_TYPE_HTML
|
||||||
|
@ -48,7 +50,7 @@ func (rs *Response) Any(body any) *Response {
|
||||||
return rs
|
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 {
|
func (rs *Response) Json(body string) *Response {
|
||||||
if rs.isTerminated == false {
|
if rs.isTerminated == false {
|
||||||
rs.contentType = CONTENT_TYPE_JSON
|
rs.contentType = CONTENT_TYPE_JSON
|
||||||
|
@ -57,7 +59,7 @@ func (rs *Response) Json(body string) *Response {
|
||||||
return rs
|
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 {
|
func (rs *Response) Text(body string) *Response {
|
||||||
if rs.isTerminated == false {
|
if rs.isTerminated == false {
|
||||||
rs.contentType = CONTENT_TYPE_TEXT
|
rs.contentType = CONTENT_TYPE_TEXT
|
||||||
|
@ -66,7 +68,7 @@ func (rs *Response) Text(body string) *Response {
|
||||||
return rs
|
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 {
|
func (rs *Response) HTML(body string) *Response {
|
||||||
if rs.isTerminated == false {
|
if rs.isTerminated == false {
|
||||||
rs.contentType = CONTENT_TYPE_HTML
|
rs.contentType = CONTENT_TYPE_HTML
|
||||||
|
@ -75,7 +77,7 @@ func (rs *Response) HTML(body string) *Response {
|
||||||
return rs
|
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 {
|
func (rs *Response) Template(name string, data interface{}) *Response {
|
||||||
var buffer bytes.Buffer
|
var buffer bytes.Buffer
|
||||||
if rs.isTerminated == false {
|
if rs.isTerminated == false {
|
||||||
|
@ -89,7 +91,7 @@ func (rs *Response) Template(name string, data interface{}) *Response {
|
||||||
return rs
|
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 {
|
func (rs *Response) SetStatusCode(code int) *Response {
|
||||||
if rs.isTerminated == false {
|
if rs.isTerminated == false {
|
||||||
rs.statusCode = code
|
rs.statusCode = code
|
||||||
|
@ -98,7 +100,7 @@ func (rs *Response) SetStatusCode(code int) *Response {
|
||||||
return rs
|
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 {
|
func (rs *Response) SetContentType(c string) *Response {
|
||||||
if rs.isTerminated == false {
|
if rs.isTerminated == false {
|
||||||
rs.overrideContentType = c
|
rs.overrideContentType = c
|
||||||
|
@ -107,7 +109,7 @@ func (rs *Response) SetContentType(c string) *Response {
|
||||||
return rs
|
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 {
|
func (rs *Response) SetHeader(key string, val string) *Response {
|
||||||
if rs.isTerminated == false {
|
if rs.isTerminated == false {
|
||||||
h := header{
|
h := header{
|
||||||
|
@ -119,10 +121,12 @@ func (rs *Response) SetHeader(key string, val string) *Response {
|
||||||
return rs
|
return rs
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// terminates the response processing, preventing any further modifications or actions.
|
||||||
func (rs *Response) ForceSendResponse() {
|
func (rs *Response) ForceSendResponse() {
|
||||||
rs.isTerminated = true
|
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 {
|
func (rs *Response) Redirect(url string) *Response {
|
||||||
validator := resolveValidator()
|
validator := resolveValidator()
|
||||||
v := validator.Validate(map[string]interface{}{
|
v := validator.Validate(map[string]interface{}{
|
||||||
|
@ -142,6 +146,7 @@ func (rs *Response) Redirect(url string) *Response {
|
||||||
return rs
|
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 {
|
func (rs *Response) castBasicVarsToString(data interface{}) string {
|
||||||
switch dataType := data.(type) {
|
switch dataType := data.(type) {
|
||||||
case string:
|
case string:
|
||||||
|
@ -199,6 +204,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() {
|
func (rs *Response) reset() {
|
||||||
rs.body = nil
|
rs.body = nil
|
||||||
rs.statusCode = http.StatusOK
|
rs.statusCode = http.StatusOK
|
||||||
|
|
13
router.go
13
router.go
|
@ -5,6 +5,7 @@
|
||||||
|
|
||||||
package core
|
package core
|
||||||
|
|
||||||
|
// Route defines an HTTP route with a method, path, controller function, and optional hooks for customization.
|
||||||
type Route struct {
|
type Route struct {
|
||||||
Method string
|
Method string
|
||||||
Path string
|
Path string
|
||||||
|
@ -12,12 +13,15 @@ type Route struct {
|
||||||
Hooks []Hook
|
Hooks []Hook
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Router represents a structure for storing and managing routes in the application.
|
||||||
type Router struct {
|
type Router struct {
|
||||||
Routes []Route
|
Routes []Route
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// router is a global instance of the Router struct used to manage and resolve application routes.
|
||||||
var router *Router
|
var router *Router
|
||||||
|
|
||||||
|
// NewRouter initializes and returns a new Router instance with an empty slice of routes.
|
||||||
func NewRouter() *Router {
|
func NewRouter() *Router {
|
||||||
router = &Router{
|
router = &Router{
|
||||||
[]Route{},
|
[]Route{},
|
||||||
|
@ -25,10 +29,12 @@ func NewRouter() *Router {
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ResolveRouter returns the singleton instance of the Router. It initializes and manages HTTP routes configuration.
|
||||||
func ResolveRouter() *Router {
|
func ResolveRouter() *Router {
|
||||||
return 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 {
|
func (r *Router) Get(path string, controller Controller, hooks ...Hook) *Router {
|
||||||
r.Routes = append(r.Routes, Route{
|
r.Routes = append(r.Routes, Route{
|
||||||
Method: GET,
|
Method: GET,
|
||||||
|
@ -39,6 +45,7 @@ func (r *Router) Get(path string, controller Controller, hooks ...Hook) *Router
|
||||||
return r
|
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 {
|
func (r *Router) Post(path string, controller Controller, hooks ...Hook) *Router {
|
||||||
r.Routes = append(r.Routes, Route{
|
r.Routes = append(r.Routes, Route{
|
||||||
Method: POST,
|
Method: POST,
|
||||||
|
@ -49,6 +56,7 @@ func (r *Router) Post(path string, controller Controller, hooks ...Hook) *Router
|
||||||
return r
|
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 {
|
func (r *Router) Delete(path string, controller Controller, hooks ...Hook) *Router {
|
||||||
r.Routes = append(r.Routes, Route{
|
r.Routes = append(r.Routes, Route{
|
||||||
Method: DELETE,
|
Method: DELETE,
|
||||||
|
@ -59,6 +67,7 @@ func (r *Router) Delete(path string, controller Controller, hooks ...Hook) *Rout
|
||||||
return r
|
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 {
|
func (r *Router) Patch(path string, controller Controller, hooks ...Hook) *Router {
|
||||||
r.Routes = append(r.Routes, Route{
|
r.Routes = append(r.Routes, Route{
|
||||||
Method: PATCH,
|
Method: PATCH,
|
||||||
|
@ -69,6 +78,7 @@ func (r *Router) Patch(path string, controller Controller, hooks ...Hook) *Route
|
||||||
return r
|
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 {
|
func (r *Router) Put(path string, controller Controller, hooks ...Hook) *Router {
|
||||||
r.Routes = append(r.Routes, Route{
|
r.Routes = append(r.Routes, Route{
|
||||||
Method: PUT,
|
Method: PUT,
|
||||||
|
@ -79,6 +89,7 @@ func (r *Router) Put(path string, controller Controller, hooks ...Hook) *Router
|
||||||
return r
|
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 {
|
func (r *Router) Options(path string, controller Controller, hooks ...Hook) *Router {
|
||||||
r.Routes = append(r.Routes, Route{
|
r.Routes = append(r.Routes, Route{
|
||||||
Method: OPTIONS,
|
Method: OPTIONS,
|
||||||
|
@ -89,6 +100,7 @@ func (r *Router) Options(path string, controller Controller, hooks ...Hook) *Rou
|
||||||
return r
|
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 {
|
func (r *Router) Head(path string, controller Controller, hooks ...Hook) *Router {
|
||||||
r.Routes = append(r.Routes, Route{
|
r.Routes = append(r.Routes, Route{
|
||||||
Method: HEAD,
|
Method: HEAD,
|
||||||
|
@ -99,6 +111,7 @@ func (r *Router) Head(path string, controller Controller, hooks ...Hook) *Router
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRoutes returns a slice of Route objects currently registered within the Router.
|
||||||
func (r *Router) GetRoutes() []Route {
|
func (r *Router) GetRoutes() []Route {
|
||||||
return r.Routes
|
return r.Routes
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue