core

package
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2025 License: GPL-3.0 Imports: 20 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 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

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

	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) IsClosed

func (c *Ctx) IsClosed() bool

IsClosed returns true if the connection is closed.

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
	Files   []FileData
	Dirs    []DirData
}

type Endpoint

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

Endpoint represents an endpoint in the application.

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 {
	Name string
	Size int64
}

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
)

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 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

BUG: Exec of HandlerFunc is not prob stopped! 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
)

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.

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 WithOpenApiTags

func WithOpenApiTags(tags ...string) RouteOption

WithOpenApiTags adds tags to the route in OpenAPI.

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.

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) 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)

func (*Router) ServeStaticFile added in v0.3.3

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

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 WithPreLoad added in v0.4.0

func WithPreLoad() StaticServFileOption

WithPreLoad it looks if files exits on startup, if not, it will return an error.

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!

type StaticSevFileConfig added in v0.3.3

type StaticSevFileConfig struct {
	// 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