core

package module
v1.9.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 24, 2025 License: MIT Imports: 44 Imported by: 0

README

Goffee Core

The core packages of Goffee framework

Documentation

Index

Constants

View Source
const CONTENT_TYPE string = "content-Type"
View Source
const CONTENT_TYPE_HTML string = "text/html; charset=utf-8"
View Source
const CONTENT_TYPE_IMAGEJPG string = "image/jpeg"
View Source
const CONTENT_TYPE_IMAGEPNG string = "image/png"
View Source
const CONTENT_TYPE_IMAGESVGXML string = "image/svg+xml"
View Source
const CONTENT_TYPE_JSON string = "application/json"
View Source
const CONTENT_TYPE_MULTIPART_FORM_DATA string = "multipart/form-data;"
View Source
const CONTENT_TYPE_TEXT string = "text/plain"
View Source
const DELETE string = "delete"
View Source
const GET string = "get"
View Source
const HEAD string = "head"
View Source
const LOCALHOST string = "http://localhost"
View Source
const OPTIONS string = "options"
View Source
const PATCH string = "patch"
View Source
const POST string = "post"
View Source
const PRODUCTION string = "production"
View Source
const PUT string = "put"
View Source
const TEST_STR string = "Testing!"

Variables

View Source
var (
	ErrValueTooLong = errors.New("cookie value too long")
	ErrInvalidValue = errors.New("invalid cookie value")
)

ErrValueTooLong indicates that the cookie value exceeds the allowed length limit. ErrInvalidValue signifies that the cookie value is in an invalid format.

Functions

func CookieRead added in v1.8.0

func CookieRead(r *http.Request, name string) (string, error)

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 CookieReadEncrypted added in v1.8.0

func CookieReadEncrypted(r *http.Request, name string, secretKey []byte) (string, error)

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 CookieWrite added in v1.8.0

func CookieWrite(w http.ResponseWriter, cookie http.Cookie) error

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 CookieWriteEncrypted added in v1.8.0

func CookieWriteEncrypted(w http.ResponseWriter, cookie http.Cookie, secretKey []byte) error

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 DisableEvents

func DisableEvents()

DisableEvents sets the global variable `disableEvents` to true, disabling the handling or triggering of events.

func EnableEvents

func EnableEvents()

EnableEvents sets the global variable `disableEvents` to false, effectively enabling event handling.

func Graph added in v1.8.2

func NewGorm

func NewGorm() *gorm.DB

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 NewTemplates added in v1.8.0

func NewTemplates(components embed.FS, templates embed.FS)

func ResolveGorm

func ResolveGorm() *gorm.DB

ResolveGorm initializes and returns a singleton instance of *gorm.DB, creating it if it doesn't already exist.

func SetCookie added in v1.8.0

func SetCookie(w http.ResponseWriter, email string, token string) error

SetCookie sets an encrypted cookie with a user's email and token, using gob encoding for data serialization.

func UseHook added in v1.7.3

func UseHook(mw Hook)

UseHook registers a Hook middleware function by attaching it to the global Hooks instance.

Types

type App

type App struct {
	Config *configContainer
	// contains filtered or unexported fields
}

App is a struct representing the main application container and its core components.

func New

func New() *App

New initializes and returns a new instance of the App structure with default configurations and chain.

func ResolveApp

func ResolveApp() *App

ResolveApp returns the global instance of the App, providing access to its methods and configuration components.

func (*App) Bootstrap

func (app *App) Bootstrap()

Bootstrap initializes the application by setting up the logger, router, and events manager.

func (*App) MakeDirs

func (app *App) MakeDirs(dirs ...string)

MakeDirs creates the specified directories under the base path with the provided permissions (0766).

func (*App) Next

func (app *App) Next(c *Context)

Next advances to the next middleware or controller in the chain and invokes it with the given context if available.

func (*App) RegisterRoutes

func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httprouter.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) RegisterTemplates added in v1.8.0

func (app *App) RegisterTemplates(templates_resources embed.FS)

RegisterTemplates initializes the application template system by embedding provided templates for rendering views.

func (*App) Run

func (app *App) Run(router *httprouter.Router)

Run initializes the application's router, configures HTTPS if enabled, and starts the HTTP/HTTPS server.

func (*App) SetBasePath

func (app *App) SetBasePath(path string)

SetBasePath sets the base path for the application, which is used as a prefix for file and directory operations.

func (*App) SetCacheConfig

func (app *App) SetCacheConfig(c CacheConfig)

SetCacheConfig sets the cache configuration for the application using the provided CacheConfig parameter.

func (*App) SetGormConfig

func (app *App) SetGormConfig(g GormConfig)

SetGormConfig sets the GormConfig for the application, overriding the current configuration with the provided value.

func (*App) SetLogsDriver

func (app *App) SetLogsDriver(d logger.LogsDriver)

SetLogsDriver sets the logging driver to be used by the application.

func (*App) SetRequestConfig

func (app *App) SetRequestConfig(r RequestConfig)

SetRequestConfig sets the configuration for the request in the application instance.

func (*App) SetRunMode added in v1.8.3

func (app *App) SetRunMode(runmode string)

SetRunMode sets the application run mode to the specified value.

type Asynqtask added in v1.9.0

type Asynqtask func(context.Context, *asynq.Task) error

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

func NewCache

func NewCache(cacheConfig CacheConfig) *Cache

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 (*Cache) Delete

func (c *Cache) Delete(key string) error

Delete removes the specified key from the cache and returns an error if the operation fails.

func (*Cache) Get

func (c *Cache) Get(key string) (string, error)

Get retrieves the value associated with the provided key from the cache. Returns an error if the operation fails.

func (*Cache) Set

func (c *Cache) Set(key string, value string) error

Set stores a key-value pair in the Redis cache with no expiration. Returns an error if the operation fails.

func (*Cache) SetWithExpiration

func (c *Cache) SetWithExpiration(key string, value string, expiration time.Duration) error

SetWithExpiration stores a key-value pair in the cache with a specified expiration duration. Returns an error if the operation fails.

type CacheConfig

type CacheConfig struct {
	EnableCache bool
}

type Context

type Context struct {
	Request          *Request
	Response         *Response
	GetValidator     func() *Validator
	GetJWT           func() *JWT
	GetGorm          func() *gorm.DB
	GetCache         func() *Cache
	GetHashing       func() *Hashing
	GetMailer        func() *Mailer
	GetEventsManager func() *EventsManager
	GetLogger        func() *logger.Logger
}

func (*Context) CastToFloat

func (c *Context) CastToFloat(value interface{}) float64

func (*Context) CastToInt

func (c *Context) CastToInt(value interface{}) int

func (*Context) CastToString

func (c *Context) CastToString(value interface{}) string

func (*Context) CopyFile

func (c *Context) CopyFile(sourceFilePath string, destFolderPath string) error

func (*Context) DebugAny

func (c *Context) DebugAny(variable interface{})

TODO enhance

func (*Context) GetBaseDirPath

func (c *Context) GetBaseDirPath() string

func (*Context) GetCookie added in v1.8.0

func (c *Context) GetCookie() (UserCookie, error)

func (*Context) GetHeader

func (c *Context) GetHeader(key string) string

func (*Context) GetPathParam

func (c *Context) GetPathParam(key string) interface{}

func (*Context) GetQueueClient added in v1.9.0

func (c *Context) GetQueueClient() *asynq.Client

func (*Context) GetRequesBodyMap added in v1.8.0

func (c *Context) GetRequesBodyMap() map[string]interface{}

func (*Context) GetRequesBodyStruct added in v1.8.0

func (c *Context) GetRequesBodyStruct(dest interface{}) error

get json body and bind to dest interface

func (*Context) GetRequesForm added in v1.8.0

func (c *Context) GetRequesForm(key string) interface{}

func (*Context) GetRequestParam

func (c *Context) GetRequestParam(key string) interface{}

func (*Context) GetUploadedFile

func (c *Context) GetUploadedFile(name string) *UploadedFileInfo

func (Context) GetUserAgent

func (c Context) GetUserAgent() string

func (*Context) MapToJson

func (c *Context) MapToJson(v any) string

func (*Context) MoveFile

func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error

func (*Context) Next

func (c *Context) Next()

func (*Context) RequestParamExists

func (c *Context) RequestParamExists(key string) bool

type Controller added in v1.7.3

type Controller func(c *Context) *Response

type EmailAddress

type EmailAddress struct {
	Name    string // the name can be empty
	Address string // ex: john@example.com
}

type EmailAttachment

type EmailAttachment struct {
	Name string // name of the file
	Path string // full path to the file
}

type EnvFileConfig

type EnvFileConfig struct {
	UseDotEnvFile bool
}

type Event

type Event struct {
	Name    string
	Payload map[string]interface{}
}

type EventJob

type EventJob func(event *Event, requestContext *Context)

type EventsManager

type EventsManager struct {
	// contains filtered or unexported fields
}

func NewEventsManager

func NewEventsManager() *EventsManager

func ResolveEventsManager

func ResolveEventsManager() *EventsManager

func (*EventsManager) Fire

func (m *EventsManager) Fire(e *Event) error

func (*EventsManager) Register

func (m *EventsManager) Register(eName string, job EventJob)

type GormConfig

type GormConfig struct {
	EnableGorm bool
}

type Hashing

type Hashing struct{}

func (*Hashing) CheckPasswordHash

func (h *Hashing) CheckPasswordHash(hashedPassword string, originalPassowrd string) (bool, error)

func (*Hashing) HashPassword

func (h *Hashing) HashPassword(password string) (string, error)

type Hook added in v1.7.3

type Hook func(c *Context)

type Hooks added in v1.7.3

type Hooks struct {
	// contains filtered or unexported fields
}

func NewHooks added in v1.7.3

func NewHooks() *Hooks

func ResolveHooks added in v1.7.3

func ResolveHooks() *Hooks

func (*Hooks) Attach added in v1.7.3

func (m *Hooks) Attach(mw Hook) *Hooks

func (*Hooks) GetHooks added in v1.7.3

func (m *Hooks) GetHooks() []Hook

type JWT

type JWT struct {
	// contains filtered or unexported fields
}

func (*JWT) DecodeToken

func (j *JWT) DecodeToken(token string) (payload map[string]interface{}, err error)

func (*JWT) GenerateToken

func (j *JWT) GenerateToken(payload map[string]interface{}) (string, error)

func (*JWT) HasExpired

func (j *JWT) HasExpired(token string) (bool, error)

type JWTConfig

type JWTConfig struct {
	SecretKey string
	Lifetime  int
}

type JWTOptions

type JWTOptions struct {
	SigningKey      string
	LifetimeMinutes int
}

type Mailer

type Mailer struct {
	// contains filtered or unexported fields
}

func (*Mailer) Send

func (m *Mailer) Send() error

func (*Mailer) SetAttachments

func (m *Mailer) SetAttachments(attachments []EmailAttachment) *Mailer

func (*Mailer) SetBCC

func (m *Mailer) SetBCC(emailAddresses []EmailAddress) *Mailer

func (*Mailer) SetCC

func (m *Mailer) SetCC(emailAddresses []EmailAddress) *Mailer

func (*Mailer) SetFrom

func (m *Mailer) SetFrom(emailAddresses EmailAddress) *Mailer

func (*Mailer) SetHTMLBody

func (m *Mailer) SetHTMLBody(body string) *Mailer

func (*Mailer) SetPlainTextBody

func (m *Mailer) SetPlainTextBody(body string) *Mailer

func (*Mailer) SetSubject

func (m *Mailer) SetSubject(subject string) *Mailer

func (*Mailer) SetTo

func (m *Mailer) SetTo(emailAddresses []EmailAddress) *Mailer

type QueueConfig added in v1.9.0

type QueueConfig struct {
	EnableQueue bool
}

type Queuemux added in v1.9.0

type Queuemux struct {
	// contains filtered or unexported fields
}

func (*Queuemux) AddWork added in v1.9.0

func (q *Queuemux) AddWork(pattern string, work Asynqtask)

func (*Queuemux) QueueInit added in v1.9.0

func (q *Queuemux) QueueInit()

func (*Queuemux) RunQueueserver added in v1.9.0

func (q *Queuemux) RunQueueserver()

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.

type Request

type Request struct {
	// contains filtered or unexported fields
}

type RequestConfig

type RequestConfig struct {
	MaxUploadFileSize int
}

type Response

type Response struct {
	HttpResponseWriter http.ResponseWriter
	// contains filtered or unexported fields
}

Response represents an HTTP response to be sent to the client, including headers, body, status code, and metadata.

func (*Response) Any

func (rs *Response) Any(body any) *Response

sets the response's content type to HTML and assigns the provided body as the response body if not terminated.

func (*Response) BufferFile added in v1.9.0

func (rs *Response) BufferFile(name string, filetype string, b bytes.Buffer) *Response

writes the contents of a buffer to the HTTP response with specified file name and type if not terminated.

func (*Response) ForceSendResponse

func (rs *Response) ForceSendResponse()

terminates the response processing, preventing any further modifications or actions.

func (*Response) HTML

func (rs *Response) HTML(body string) *Response

sets the response's content type to HTML and assigns the provided string as the body if the response is not terminated.

func (*Response) Json

func (rs *Response) Json(body string) *Response

sets the response's content type to JSON and assigns the provided string as the body if the response is not terminated.

func (*Response) Redirect

func (rs *Response) Redirect(url string) *Response

updates the redirect URL for the response and returns the modified Response. Validates the URL before setting it.

func (*Response) SetContentType

func (rs *Response) SetContentType(c string) *Response

sets a custom content type for the response if it is not terminated. Returns the updated Response object.

func (*Response) SetHeader

func (rs *Response) SetHeader(key string, val string) *Response

adds or updates a header to the response if it is not terminated. Returns the updated Response object.

func (*Response) SetStatusCode

func (rs *Response) SetStatusCode(code int) *Response

sets the response status code if the response is not yet terminated. Returns the updated Response object.

func (*Response) Template added in v1.8.0

func (rs *Response) Template(name string, data interface{}) *Response

renders the specified template with the provided data and writes the result to the HTTP response if not terminated.

func (*Response) Text

func (rs *Response) Text(body string) *Response

sets the response's content type to plain text and assigns the provided string as the body if not terminated.

type Route

type Route struct {
	Method     string
	Path       string
	Controller Controller
	Hooks      []Hook
}

Route defines an HTTP route with a method, path, controller function, and optional hooks for customization.

type Router

type Router struct {
	Routes []Route
}

Router represents a structure for storing and managing routes in the application.

func NewRouter

func NewRouter() *Router

NewRouter initializes and returns a new Router instance with an empty slice of routes.

func ResolveRouter

func ResolveRouter() *Router

ResolveRouter returns the singleton instance of the Router. It initializes and manages HTTP routes configuration.

func (*Router) Delete

func (r *Router) Delete(path string, controller Controller, hooks ...Hook) *Router

Delete registers a DELETE HTTP method route with the specified path, controller, and optional hooks.

func (*Router) Get

func (r *Router) Get(path string, controller Controller, hooks ...Hook) *Router

Get registers a GET route with the specified path, controller, and optional hooks, returning the updated Router.

func (*Router) GetRoutes

func (r *Router) GetRoutes() []Route

GetRoutes returns a slice of Route objects currently registered within the Router.

func (*Router) Head

func (r *Router) Head(path string, controller Controller, hooks ...Hook) *Router

Head registers a route with the HTTP HEAD method, associates it with a path, controller, and optional hooks.

func (*Router) Options

func (r *Router) Options(path string, controller Controller, hooks ...Hook) *Router

Options registers a new route with the OPTIONS HTTP method, a specified path, controller, and optional hooks.

func (*Router) Patch

func (r *Router) Patch(path string, controller Controller, hooks ...Hook) *Router

Patch registers a new route with the HTTP PATCH method, a specified path, a controller, and optional hooks.

func (*Router) Post

func (r *Router) Post(path string, controller Controller, hooks ...Hook) *Router

Post registers a route with the HTTP POST method, associating it with the given path, controller, and optional hooks.

func (*Router) Put

func (r *Router) Put(path string, controller Controller, hooks ...Hook) *Router

Put registers a new route with the HTTP PUT method, associating it to the given path, controller, and optional hooks.

type UploadedFileInfo

type UploadedFileInfo struct {
	FullPath             string
	Name                 string
	NameWithoutExtension string
	Extension            string
	Size                 int
}

type UserCookie added in v1.8.0

type UserCookie struct {
	Email string
	Token string
}

UserCookie represents a structure to hold user-specific data stored in a cookie, including Email and Token fields.

func GetCookie added in v1.8.0

func GetCookie(r *http.Request) (UserCookie, error)

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.

type Validator

type Validator struct{}

func (*Validator) Validate

func (v *Validator) Validate(data map[string]interface{}, rules map[string]interface{}) validationResult

Directories

Path Synopsis
template

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL