core

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2025 License: GPL-3.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateDummyDir added in v0.3.5

func CreateDummyDir(dirPath string) error

func ReadDummyFile added in v0.5.3

func ReadDummyFile(filePath string) (string, error)

func RemoveDummyDir added in v0.3.5

func RemoveDummyDir(dirPath string) error

func RemoveDummyFile added in v0.3.5

func RemoveDummyFile(filePath string) error

func WriteDummyFile added in v0.3.5

func WriteDummyFile(filePath, content string) error

Types

type ApiResponse

type ApiResponse struct {
	Headers           map[string]string
	StatusCode        int    `json:"statusCode" xml:"statusCode"`
	InternalErrorCode int    ``
	Message           string `json:"message" xml:"message"`
	Data              []byte `json:"data,omitempty" xml:"data,omitempty"`
}

ApiResponse is the standard API response.

func NewApiResponse

func NewApiResponse() *ApiResponse

NewApiResponse creates a new ApiResponse.

func (*ApiResponse) AddHeader

func (r *ApiResponse) AddHeader(k, v string)

AddHeader adds a header to the response.

func (*ApiResponse) Redirect added in v0.4.0

func (r *ApiResponse) Redirect(url string, code int)

Redirect performs a redirect.

func (*ApiResponse) SetData

func (r *ApiResponse) SetData(data []byte)

SetData sets the data of the response.

func (*ApiResponse) SetMessage

func (r *ApiResponse) SetMessage(msg string)

SetMessage sets the message of the response.

func (*ApiResponse) SetMessagef added in v0.3.7

func (r *ApiResponse) SetMessagef(msg string, a ...any)

SetMessage sets the message of the response.

func (*ApiResponse) SetStatus

func (r *ApiResponse) SetStatus(code int)

SetStatus sets the status code of the response.

type App

type App struct {
	Logger logger.Logger
	// contains filtered or unexported fields
}

App is the main application struct. TODO: Implement a middleware to limit the maximum number of concurrent connections to prevent server overload. TODO: Implement a middleware for rate limiting to control the number of requests a client can make within a specific time frame. TODO: Implement a middleware to compress HTTP responses (e.g., using gzip or brotli) to reduce bandwidth usage. TODO: Implement a middleware for response caching to store and serve frequently requested responses, improving performance. TODO: Enhance the Middleware interface to include a mechanism (e.g., a 'Next' or 'Skip' function) allowing middlewares to conditionally bypass subsequent middlewares or handlers based on certain criteria (e.g., specific endpoints or request states).

func NewApp

func NewApp(opts ...AppOption) App

NewApp creates a new App instance.

func (*App) DELETE

func (a *App) DELETE(path string, handler Handler, opt ...RouteOption)

func (*App) GET

func (a *App) GET(path string, handler Handler, opt ...RouteOption)

func (*App) NewRouter

func (a *App) NewRouter(path string) *Router

TODO: Add RoutOptions NewRouter creates a new router with a given base path.

func (*App) OPTIONS

func (a *App) OPTIONS(path string, handler Handler, opt ...RouteOption)

func (*App) POST

func (a *App) POST(path string, handler Handler, opt ...RouteOption)

func (*App) PUT

func (a *App) PUT(path string, handler Handler, opt ...RouteOption)

func (*App) Redirect added in v0.4.0

func (a *App) Redirect(path, url string, code int)

func (*App) Run

func (a *App) Run() error

func (*App) ServeStaticDir added in v0.3.3

func (a *App) ServeStaticDir(urlPath, dirPath string, opt ...StaticServFileOption)

func (*App) ServeStaticFile added in v0.3.3

func (a *App) ServeStaticFile(urlPath, filePath string, opt ...StaticServFileOption)

func (*App) SetDefaultRoute

func (a *App) SetDefaultRoute(handler Handler)

SetDefaultRoute sets the default route handler for the application.

func (*App) SetLogger

func (a *App) SetLogger(logger logger.Logger)

SetLogger sets the logger for the application.

func (*App) SetTimeout added in v0.3.4

func (a *App) SetTimeout(timeout time.Duration)

SetTimeout configures the request timeout for the application

func (*App) SetTimeoutConfig added in v0.3.4

func (a *App) SetTimeoutConfig(config TimeoutConfig)

SetTimeoutConfig configures the complete timeout configuration for the application

func (*App) Use added in v0.3.4

func (a *App) Use(m Middleware)

type AppConfig

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

AppConfig holds the configuration for the application.

func (AppConfig) GetListenAddress

func (c AppConfig) GetListenAddress() string

GetListenAddress returns the address the application will listen on.

type AppOption

type AppOption func(*AppConfig)

AppOption is a function that configures an AppConfig.

func AppAddServer

func AppAddServer(url, description string) AppOption

AppAddServer adds a server to the list of servers for the application.

func AppAddr

func AppAddr(host, port string) AppOption

AppAddr sets the host and port the application will listen on.

func AppContact

func AppContact(name, email, url string) AppOption

AppContact sets the contact information for the application.

func AppDescription

func AppDescription(description string) AppOption

AppDescription sets the description of the application.

func AppLicense

func AppLicense(name, url string) AppOption

AppLicense sets the license information for the application.

func AppLogger

func AppLogger(logger logger.Logger) AppOption

AppLogger sets the logger for the application.

func AppTimeout added in v0.3.4

func AppTimeout(timeout time.Duration) AppOption

AppTimeout sets the timeout for the application.

func AppTitle

func AppTitle(title string) AppOption

AppTitle sets the title of the application.

func AppVersion

func AppVersion(version string) AppOption

AppVersion sets the version of the application.

type CORSConfig

type CORSConfig struct {
	// AllowOrigins is a list of origins a cross-domain request can be executed from.
	// If the special "*" value is present in the list, all origins will be allowed.
	// Default value is ["*"]
	AllowOrigins []string

	// AllowMethods is a list of methods the client is allowed to use with
	// cross-domain requests. Default value is simple methods (GET, POST, PUT, DELETE)
	AllowMethods []string

	// AllowHeaders is a list of non-simple headers the client is allowed to use with
	// cross-domain requests. Default value is []
	AllowHeaders []string

	// ExposeHeaders indicates which headers are safe to expose to the API of a CORS
	// API specification. Default value is []
	ExposeHeaders []string

	// AllowCredentials indicates whether the request can include user credentials like
	// cookies, HTTP authentication or client side SSL certificates. Default is false.
	AllowCredentials bool

	// MaxAge indicates how long (in seconds) the results of a preflight request
	// can be cached. Default is 0 which stands for no max age.
	MaxAge int
}

CORSConfig holds the configuration for CORS middleware

func DefaultCORSConfig

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig returns a default CORS configuration

func ExposeAllCORSConfig added in v0.3.5

func ExposeAllCORSConfig() CORSConfig

ExposeAllCORSConfig returns a CORSConfig that allows all origins, headers, and methods. Use with caution! But might be nice for dev/testing.

type CSRFConfig added in v0.4.0

type CSRFConfig struct {
	// TokenLength is the length of the CSRF token
	TokenLength uint8
	// CookieName is the name of the CSRF cookie
	CookieName string
	// CookiePath is the path of the CSRF cookie
	CookiePath string
	// CookieExpires is the expiration time of the CSRF cookie
	CookieExpires time.Duration
	// CookieSecure is the secure flag of the CSRF cookie
	CookieSecure bool
	// CookieHTTPOnly is the HTTPOnly flag of the CSRF cookie
	CookieHTTPOnly bool
	// HeaderName is the name of the CSRF header
	HeaderName string
}

CSRFConfig holds the configuration for the CSRF middleware

func DefaultCSRFConfig added in v0.4.0

func DefaultCSRFConfig() CSRFConfig

DefaultCSRFConfig returns a default CSRF configuration

type CrudInterface added in v0.3.7

type CrudInterface interface {
	CreateFunc(any) (any, error)
	ReadAllFunc() ([]any, error)
	ReadOneFunc(any) (any, error)
	UpdateFunc(any, any) (any, error)
	DeleteFunc(any) (any, error)
}

TODO: Add a ReadMulti method to the CrudInterface and implement corresponding router functionality to allow fetching multiple resources based on criteria. TODO: Add BulkUpdate, BulkDelete, and BulkCreate methods to the CrudInterface and implement corresponding router functionalities for efficient batch operations. TODO: Implement a mechanism to allow setting individual RouteOptions for each endpoint generated by the CRUD function, overriding the general CRUD options.

type Ctx

type Ctx struct {
	// TODO: Refactor ApiResponse to an interface (e.g., ResponseWriter) to allow for different response types, such as HTML responses, beyond just API responses.
	Response *ApiResponse
	Request  *http.Request

	PathParams  map[string]string
	QueryParams map[string]string
	Session     map[string]any

	ObjIn     any
	ObjInType reflect.Type

	ObjOut     any
	ObjOutType reflect.Type
	// contains filtered or unexported fields
}

Ctx is the context for a request.

func NewCtx

func NewCtx(w http.ResponseWriter, r *http.Request, route Route, ep Endpoint) *Ctx

NewCtx creates a new Ctx instance.

func (*Ctx) Close

func (c *Ctx) Close()

Close closes the connection.

func (*Ctx) ConClosed added in v0.6.0

func (c *Ctx) ConClosed() <-chan bool

ConClosed returns the connection closed channel.

func (*Ctx) GetConnectionDuration added in v0.6.0

func (c *Ctx) GetConnectionDuration() time.Duration

GetConnectionDuration returns the duration of the connection.

func (*Ctx) IsClosed

func (c *Ctx) IsClosed() bool

IsClosed returns true if the connection is closed.

func (*Ctx) SaveFile added in v0.5.3

func (c *Ctx) SaveFile(formKey, dstPath string, opts ...FileSaveOption) error

func (*Ctx) SendingReturn added in v0.3.5

func (c *Ctx) SendingReturn(w http.ResponseWriter, err error)

SendingReturn sends the response to the client.

type DirData added in v0.4.0

type DirData struct {
	Name string
}

type DirTemplateData added in v0.4.0

type DirTemplateData struct {
	Title           string
	BaseUrl         string
	IndexFileExists bool
	Files           []FileData
	Dirs            []DirData
}

type DummyFile added in v0.5.3

type DummyFile struct {
	Body        *bytes.Buffer
	ContentType string
}

DummyFile represents a dummy file created for testing purposes.

func CreateDummyMultipartFile added in v0.5.3

func CreateDummyMultipartFile(fileName, fileContent string) (*DummyFile, error)

type Endpoint

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

Endpoint represents an endpoint in the application.

func (Endpoint) GetMethod added in v0.6.0

func (e Endpoint) GetMethod() RequestMethod

GetMethod returns the endpoint method

func (Endpoint) GetRouteOptionConfig added in v0.6.0

func (e Endpoint) GetRouteOptionConfig() RouteOptionConfig

GetRouteOptionConfig returns the route option config

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error" xml:"error" description:"Error message"`
	Code    int    `json:"code" xml:"code" description:"Error code"`
	Details string `json:"details,omitempty" xml:"details,omitempty" description:"Additional error details"`
}

ErrorResponse is the response for errors.

type FileData added in v0.4.0

type FileData struct {
	DirPath string
	Name    string
	Size    int64
}

type FileSaveConfig added in v0.5.3

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

func NewFileSaveConfig added in v0.5.3

func NewFileSaveConfig(opts ...FileSaveOption) *FileSaveConfig

type FileSaveOption added in v0.5.3

type FileSaveOption func(*FileSaveConfig)

func WithOverwrite added in v0.5.3

func WithOverwrite() FileSaveOption

WithOverwrite overwrites the file if it already exists.

type Handler

type Handler func(*Ctx) error

Handler is a function that handles a request.

type MIMEType added in v0.3.7

type MIMEType int
const (
	MIMETYPE_JSON MIMEType = iota
	MIMETYPE_XML
	MIMETYPE_YAML
	MIMETYPE_FORM_URL
	MIMETYPE_MULTIPART_FORM_DATA
	MIMETYPE_OCTET_STREAM
	MIMETYPE_TEXT
)

func (MIMEType) ToString added in v0.6.0

func (m MIMEType) ToString() string

type Middleware

type Middleware func(Handler) Handler

Middleware is a function that wraps a Handler to add functionality. TODO: Define a consistent error handling strategy for middlewares, considering whether errors should be returned directly by the middleware or propagated through the Ctx object.

func CORSMiddleware

func CORSMiddleware(config CORSConfig) Middleware

CORSMiddleware returns a middleware that handles CORS

func CSRFMiddleware added in v0.4.0

func CSRFMiddleware(config CSRFConfig) Middleware

CSRFMiddleware returns a middleware that handles CSRF

func FavIcon added in v0.5.0

func FavIcon(filePath string) Middleware

FavIcon is a middleware that serves a favicon.ico file filePath should be the relative path to the favicon.ico file

func LogMiddleware

func LogMiddleware(logger logger.Logger) Middleware

LogMiddleware is a middleware that logs requests.

func PanicMiddleware

func PanicMiddleware() Middleware

PanicMiddleware is a middleware that recovers from panics.

func TimeoutMiddleware added in v0.3.4

func TimeoutMiddleware(config TimeoutConfig) Middleware

TODO: Implement proper handler cancellation on timeout to prevent goroutine leaks TimeoutMiddleware returns a middleware that handles request timeouts

type RequestMethod

type RequestMethod int

RequestMethod is the HTTP request method.

const (
	// METHOD_GET is the GET HTTP method.
	METHOD_GET RequestMethod = iota
	// METHOD_POST is the POST HTTP method.
	METHOD_POST
	// METHOD_PUT is the PUT HTTP method.
	METHOD_PUT
	// METHOD_PATCH is the PATCH HTTP method.
	METHOD_PATCH
	// METHOD_DELETE is the DELETE HTTP method.
	METHOD_DELETE
	// METHOD_HEAD is the HEAD HTTP method.
	METHOD_HEAD
	// METHOD_OPTIONS is the OPTIONS HTTP method.
	METHOD_OPTIONS
	// METHOD_TRACE is the TRACE HTTP method.
	METHOD_TRACE
	// METHOD_CONNECT is the CONNECT HTTP method.
	METHOD_CONNECT
)

func (RequestMethod) ToPathString added in v0.6.0

func (m RequestMethod) ToPathString() string

type Response

type Response any

Response is a generic response type.

type Route

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

Route represents a route in the application.

func (*Route) GetEndpoints added in v0.6.0

func (r *Route) GetEndpoints() []Endpoint

GetEndpoints returns the route endpoints

func (*Route) GetPath added in v0.6.0

func (r *Route) GetPath() string

GetPath returns the route path

type RouteOption

type RouteOption func(*RouteOptionConfig)

RouteOption is a function that configures a RouteOptionConfig.

func Use added in v0.3.4

func Use(m Middleware) RouteOption

Use adds a middleware to the route.

func WithObjIn

func WithObjIn(obj any) RouteOption

WithObjIn sets the input object for the route.

func WithObjOut

func WithObjOut(obj any) RouteOption

WithObjOut sets the output object for the route.

func WithOpenApiDeprecated

func WithOpenApiDeprecated() RouteOption

WithOpenApiDeprecated marks the route as deprecated in OpenAPI.

func WithOpenApiDisabled

func WithOpenApiDisabled() RouteOption

WithOpenApiDisabled disables OpenAPI generation for the route.

func WithOpenApiEnabled

func WithOpenApiEnabled(summary, description string) RouteOption

WithOpenApiEnabled enables OpenAPI generation for the route.

func WithOpenApiInfos

func WithOpenApiInfos(summary, description string) RouteOption

WithOpenApiInfos sets the OpenAPI summary and description for the route.

func WithOpenApiJwtAuth added in v0.5.5

func WithOpenApiJwtAuth() RouteOption

WithOpenApiJwtAuth enables JWT authentication for the route in OpenAPI.

func WithOpenApiTags

func WithOpenApiTags(tags ...string) RouteOption

WithOpenApiTags adds tags to the route in OpenAPI.

func WithQueryParam added in v0.5.4

func WithQueryParam(name, description string, required bool, t reflect.Type) RouteOption

type RouteOptionConfig

type RouteOptionConfig struct {
	ObjIn  any
	ObjOut any
	// contains filtered or unexported fields
}

RouteOptionConfig holds the configuration for a route. TODO: Integrate RouteOptionConfig into the Router to allow setting default values for routes defined within that router, which can then be overridden by individual route options.

func NewRouteOptionConfig

func NewRouteOptionConfig(opts ...RouteOption) *RouteOptionConfig

NewRouteOptionConfig creates a new RouteOptionConfig.

func (RouteOptionConfig) GetOpenApiConfig added in v0.6.0

func (c RouteOptionConfig) GetOpenApiConfig() struct {
	Summary, Description string
	Tags                 []string
	Deprecated           bool
	JwtAuth              bool
}

GetOpenApiConfig returns the OpenAPI configuration

func (RouteOptionConfig) GetOpenApiEnabled added in v0.6.0

func (c RouteOptionConfig) GetOpenApiEnabled() bool

GetOpenApiEnabled returns whether OpenAPI is enabled

func (RouteOptionConfig) GetQueryParams added in v0.6.0

func (c RouteOptionConfig) GetQueryParams() []struct {
	Name, Description string
	Required          bool
	Type              reflect.Type
	Example           any
}

GetQueryParams returns the query parameters

type Router

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

Router is a router for the application.

func (*Router) DELETE

func (r *Router) DELETE(path string, handler Handler, opt ...RouteOption)

DELETE adds a DELETE endpoint to the router.

func (*Router) GET

func (r *Router) GET(path string, handler Handler, opt ...RouteOption)

GET adds a GET endpoint to the router.

func (Router) GetBasePath

func (r Router) GetBasePath() string

GetBasePath returns the base path of the router.

func (*Router) GetGroups added in v0.6.0

func (r *Router) GetGroups() []*Router

GetGroups returns the router groups

func (*Router) GetRoutes added in v0.6.0

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

GetRoutes returns the router routes

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handler Handler, opt ...RouteOption)

OPTIONS adds an OPTIONS endpoint to the router.

func (*Router) POST

func (r *Router) POST(path string, handler Handler, opt ...RouteOption)

POST adds a POST endpoint to the router.

func (*Router) PUT

func (r *Router) PUT(path string, handler Handler, opt ...RouteOption)

PUT adds a PUT endpoint to the router.

func (*Router) Redirect added in v0.4.0

func (r *Router) Redirect(path, targetURL string, code int)

Redirect adds a redirect to the router.

func (*Router) ServeStaticDir added in v0.3.3

func (r *Router) ServeStaticDir(urlPath, dirPath string, a *App, opt ...StaticServFileOption)

ServeStaticDir serves a directory at the given URL path. If the directory contains a "index.html" file, it will be served as "/" route. If not a FileExplorer will be shown, by default. It is highly recommended to leave the PreLoad option enabled.

func (*Router) ServeStaticFile added in v0.3.3

func (r *Router) ServeStaticFile(urlPath, filePath string, opt ...StaticServFileOption)

ServeStaticFile serves a static file.

func (*Router) Use added in v0.3.4

func (r *Router) Use(m Middleware)

Use adds a middleware to the router.

type StaticServFileOption added in v0.3.3

type StaticServFileOption func(*StaticSevFileConfig)

StaticServFileOption is a function that configures a StaticSevFileConfig.

func WithContentType added in v0.3.3

func WithContentType(contentType string) StaticServFileOption

WithContentType sets the content type of the file.

func WithIndexFile added in v0.5.0

func WithIndexFile(indexFile string) StaticServFileOption

WithIndexFile sets the index file for the directory.

func WithPreCache added in v0.3.3

func WithPreCache() StaticServFileOption

WithPreCache it will load files into memory on startup, even if bigger than the maxPreCacheSize. Caching will mainly reduce latency. With NVME drives, the speed difference is negligible.

func WithPreCacheSize added in v0.5.0

func WithPreCacheSize(size int64) StaticServFileOption

WithPreCacheSize sets the maximum size of the pre-cache.

func WithTitle added in v0.6.0

func WithTitle(title string) StaticServFileOption

WithTitle sets the title for the directory listing page.

func WithoutPreCache added in v0.5.0

func WithoutPreCache() StaticServFileOption

WithoutPreCache it will not cache files on startup.

func WithoutPreLoad added in v0.4.0

func WithoutPreLoad() StaticServFileOption

WithoutPreLoad it will not look if files exits on startup! Be careful if using this option with a Directory, this function will expose all files in the directory, even if created after Server start! This will also disable pre-caching.

type StaticSevFileConfig added in v0.3.3

type StaticSevFileConfig struct {
	Title string
	// contains filtered or unexported fields
}

StaticSevFileConfig holds the configuration for serving a static file.

func NewStaticServeFileConfig added in v0.3.3

func NewStaticServeFileConfig(opts ...StaticServFileOption) *StaticSevFileConfig

NewStaticServeFileConfig creates a new StaticSevFileConfig.

type TimeoutConfig added in v0.3.4

type TimeoutConfig struct {
	// Timeout is the maximum duration for a request to complete
	// Default is 30 seconds
	Timeout time.Duration

	// TimeoutMessage is the message returned when a request times out
	// Default is "Request timeout"
	TimeoutMessage string

	// TimeoutStatusCode is the HTTP status code returned when a request times out
	// Default is 408 (Request Timeout)
	TimeoutStatusCode int
}

TimeoutConfig holds the configuration for timeout middleware

func DefaultTimeoutConfig added in v0.3.4

func DefaultTimeoutConfig() TimeoutConfig

DefaultTimeoutConfig returns a default timeout configuration

func TimeoutConfigFromApp added in v0.3.4

func TimeoutConfigFromApp(a App) TimeoutConfig

TimeoutConfigFromApp returns a TimeoutConfig from an App instance.

Jump to

Keyboard shortcuts

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