bolo

package module
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2024 License: GPL-3.0 Imports: 48 Imported by: 20

README

Bolo

Bolo is a powerful and high-performance web framework for Go, equipped with a built-in plugin system and an extensive range of modules to streamline web application development. Designed with performance and scalability in mind, Bolo empowers developers to build robust web applications effortlessly.

Note: Bolo is currently under active development, and as such, it may undergo significant changes. Please exercise caution when using it in production environments.

Features

  • High performance: Bolo is meticulously crafted to be fast and efficient, making it the ideal choice for building high-performance web programs, allowing you to build scalable applications.
  • Plugin system: The framework use a flexible and adaptable plugin system, enabling developers to extend its functionality effortlessly. You can easily customize your application by integrating various plugins.
  • Modularity: Bolo provides an assortment of modules to simplify common tasks like routing, authentication, database integration, and more. Developers have the flexibility to cherry-pick the modules that best suit their project's requirements and seamlessly integrate them.
  • Ease of use: With a simple and intuitive API, Bolo allows developers, even those new to the Go language, to swiftly develop web applications without a steep learning curve.
  • Middleware Support: Bolo comes with robust middleware support, allowing developers to enhance the request-response cycle with pre-processing and post-processing tasks. You can easily integrate middleware into your application's pipeline to add functionalities like logging, compression, and authentication.
  • WebSocket Support: Bolo includes built-in WebSocket support, enabling real-time bidirectional communication between clients and the server. You can easily implement interactive features such as chat applications, live notifications, and collaborative tools using Bolo's WebSocket capabilities.

Installation

To get started with Bolo, ensure you have Go installed and properly configured on your system. Once Go is set up, you can install the framework using the following command:

go get github.com/go-bolo/bolo

Getting Started

Here's a simple example of how you create a simple Bolo application without plugins and MVC structure:

package main

import (
	"github.com/go-bolo/bolo"
)

func main() {
	app := bolo.New()
	app.Get("/", func(c *bolo.Context) {
		c.String(200, "Hello, Bolo!")
	})

	app.GetRouter().GET("/api", func(c *bolo.Context) {
		c.String(200, "Hello, Bolo!")
	})

	err = app.Bootstrap()
	if err != nil {
		panic(err)
	}

	err := app.StartHTTPServer()
	if err != nil {
		panic(err)
	}

}

For more detailed instructions and examples, please refer to the documentation.

Core events

Bolo core event is powered by: https://github.com/gookit/event

  • configuration: This event is triggered during the application's initialization phase when the configuration is being loaded. Developers can use this event to modify or extend the configuration before it's used by the application.
  • bindMiddlewares: When this event is fired, Bolo is ready to bind middleware functions to the application's request-response cycle. Developers can register their custom middleware or perform additional setup for existing middleware.
  • bindRoutes: This event is fired when the application is ready to bind routes to the router. Developers can use this event to register their application's routes, defining the URL endpoints and their corresponding handlers.
  • setResponseFormats: When this event is triggered, developers can define or modify the supported response formats for the application.
  • bootstrap: The 'bootstrap' event is the last event fired during the application's initialization process, indicating that the application is fully initialized and ready to start serving requests. Developers can perform any final setup or initialization tasks here.

Testing and Benchmarking

Bolo provides built-in testing and benchmarking support, allowing you to ensure the reliability and performance of your web applications effortlessly.

Contributing

We welcome and encourage contributions from the community. If you have any ideas, suggestions, or bug report, please don't hesitate to open an issue or submit a pull request on the GitHub repository.

Tricks and Tips

  • Use Plugins Wisely: Take advantage of Bolo's plugin system to enhance the functionality of your web application. Be cautious when selecting plugins and ensure they are well-maintained and compatible with the Bolo version you are using.
  • Leverage Modularity: Bolo's modular design allows you to pick and choose only the components you need for your project. This can help keep your application lightweight and efficient.
  • Benchmark Your Code: Use Bolo's built-in benchmarking support to identify performance bottlenecks in your code. Regularly benchmark your application to ensure it meets your performance requirements.
  • Error Handling Best Practices: Implement robust error handling in your application to provide meaningful feedback to users and make troubleshooting easier.
  • Security Considerations: When deploying Bolo in production environments, pay special attention to security measures, such as input validation, secure authentication, and protection against common web vulnerabilities.
  • Cautious Shutdown: Implement a graceful shutdown mechanism for your Bolo application to handle server shutdowns smoothly and avoid potential data loss or corruption.
  • Join the Community: Engage with the Bolo community to seek help, share experiences, and contribute to the project's development.
  • Stay Updated: Keep an eye on Bolo's GitHub repository for updates, bug fixes, and new features. Regularly update your Bolo installation to benefit from the latest improvements.

Core events:

Request lifecycle
  • set-default-request-context-values
    • Set default values on echo context:

License

Bolo is released under the MIT License.

Bolo is a game-changer for Go developers, providing a combination of speed, flexibility, and simplicity. Whether you're building a small web application or a large-scale project, Bolo's powerful features and modular approach will help you create top-notch web experiences with ease. Join the Bolo community today and elevate your web development journey to new heights!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var SanitizerDefault *bluemonday.Policy

Functions

func BindMiddlewares

func BindMiddlewares(app App, p *Plugin)

BindMiddlewares - Bind middlewares in order

func Copy

func Copy(header http.Header) http.Header

Copy returns a shallow copy of the header.

func CustomHTTPErrorHandler

func CustomHTTPErrorHandler(app App) func(err error, c echo.Context)

func Down added in v1.1.0

func Down(app App) error

func GetDefaultDatabaseConnection

func GetDefaultDatabaseConnection() *gorm.DB

func GetQueryInt64FromReq

func GetQueryInt64FromReq(param string, c echo.Context) int64

func GetQueryIntFromReq

func GetQueryIntFromReq(param string, c echo.Context) int

func GetSanitizer

func GetSanitizer() *bluemonday.Policy

func HealthCheckHandler

func HealthCheckHandler(c echo.Context) error

func InitSanitizer

func InitSanitizer()

func IsPublicRoute

func IsPublicRoute(url string) bool

func MinifiAndRender

func MinifiAndRender(code int, name string, data interface{}, c *RequestContext) error

func MinifiHTML

func MinifiHTML(templateName string, data interface{}, c *RequestContext) (string, error)

func NegotiateContentType

func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) string

NegotiateContentType returns the best offered content type for the request's Accept header. If two offers match with equal weight, then the more specific offer is preferred. For example, text/* trumps */*. If two offers match with equal weight and specificity, then the offer earlier in the list is preferred. If no offers match, then defaultOffer is returned.

func ParseHTTPCodeToStatus added in v1.1.4

func ParseHTTPCodeToStatus(status int) string

func ParseList

func ParseList(header http.Header, key string) []string

ParseList parses a comma separated list of values. Commas are ignored in quoted strings. Quoted values are not unescaped or unquoted. Whitespace is trimmed.

func ParseTime

func ParseTime(header http.Header, key string) time.Time

ParseTime parses the header as time. The zero value is returned if the header is not present or there is an error parsing the header.

func ParseValueAndParams

func ParseValueAndParams(header http.Header, key string) (value string, params map[string]string)

ParseValueAndParams parses a comma separated list of values with optional semicolon separated name-value pairs. Content-Type and Content-Disposition headers are in this format.

func Up added in v1.1.0

func Up(app App) error

Types

type AcceptSpec

type AcceptSpec struct {
	Value string
	Q     float64
}

AcceptSpec describes an Accept* header.

func ParseAccept

func ParseAccept(header http.Header, key string) (specs []AcceptSpec)

ParseAccept parses Accept* headers.

type Action

type Action func(ctx echo.Context) error

type App

type App interface {
	RegisterPlugin(p Pluginer)
	GetPlugins() []Pluginer
	GetPlugin(name string) Pluginer
	SetPlugin(name string, plugin Pluginer) error

	GetClock() clock.Clock
	SetClock(clock clock.Clock) error

	GetDefaultContentType() string
	GetContentTypes() []string
	SetContentTypes(contentTypes []string) error
	GetRouter() *echo.Echo
	SetRouterGroup(name, path string) *echo.Group
	GetRouterGroup(name string) *echo.Group
	SetResource(name string, httpController HTTPController, routerGroup *echo.Group) error
	StartHTTPServer() error
	NewRequestContext(opts *RequestContextOpts) *RequestContext
	// Get default app theme
	GetTheme() string
	// Set default app theme
	SetTheme(theme string) error
	// Get default app layout
	GetLayout() string
	// Set default app layout
	SetLayout(layout string) error
	GetTemplates() *template.Template
	LoadTemplates() error
	SetTemplateFunction(name string, f interface{})
	RenderTemplate(wr io.Writer, name string, data interface{}) error

	InitDatabase(name, engine string, isDefault bool) error
	SetModel(name string, f interface{})
	GetModel(name string) interface{}

	Can(permission string, userRoles []string) bool
	SetRole(name string, role acl.Role) error
	GetRoles() map[string]*acl.Role
	GetRole(name string) *acl.Role
	SetRolePermission(name string, permission string, hasAccess bool) error
	GetRolePermission(name string, permission string) bool

	GetEvents() *event.Manager

	GetConfiguration() configuration.ConfigurationInterface

	// HTML / Text sanitizer:
	GetSanitizer() *bluemonday.Policy
	SetSanitizer(policy *bluemonday.Policy) error

	GetDB() *gorm.DB
	SetDB(db *gorm.DB) error
	Migrate() error

	Bootstrap() error
	Close() error
}

func GetApp

func GetApp() App

func Init

func Init(options *AppOptions) App

func NewApp

func NewApp(options *AppOptions) App

type AppOptions

type AppOptions struct {
	DefaultContentType string
	// Avaiblable content types for negotiation:
	ContentTypes []string
	// Gorm configurations / options
	GormOptions gorm.Option
}

type AppStruct

type AppStruct struct {
	InitTime time.Time

	Options *AppOptions

	Events *event.Manager

	Configuration configuration.ConfigurationInterface
	// Default database
	DB *gorm.DB `json:"-"`
	// avaible databases
	DBs map[string]*gorm.DB `json:"-"`

	Plugins []Pluginer

	Models map[string]interface{}

	Resources map[string]*HTTPResource

	RolesString string
	RolesList   map[string]*acl.Role
	// default theme for HTML responses
	Theme string
	// default layout for HTML responses
	Layout string
	// contains filtered or unexported fields
}

func (*AppStruct) Bootstrap

func (r *AppStruct) Bootstrap() error

func (*AppStruct) Can

func (r *AppStruct) Can(permission string, userRoles []string) bool

func (*AppStruct) Close

func (r *AppStruct) Close() error

Method for close and end all app operations, use that before close the app execution

func (*AppStruct) GetClock

func (app *AppStruct) GetClock() clock.Clock

func (*AppStruct) GetConfiguration

func (r *AppStruct) GetConfiguration() configuration.ConfigurationInterface

func (*AppStruct) GetContentTypes added in v1.0.1

func (app *AppStruct) GetContentTypes() []string

func (*AppStruct) GetDB

func (r *AppStruct) GetDB() *gorm.DB

func (*AppStruct) GetDefaultContentType added in v1.0.1

func (app *AppStruct) GetDefaultContentType() string

func (*AppStruct) GetEvents

func (r *AppStruct) GetEvents() *event.Manager

func (*AppStruct) GetLayout

func (r *AppStruct) GetLayout() string

Get default app layout

func (*AppStruct) GetModel

func (r *AppStruct) GetModel(name string) interface{}

func (*AppStruct) GetPlugin

func (r *AppStruct) GetPlugin(name string) Pluginer

func (*AppStruct) GetPlugins

func (r *AppStruct) GetPlugins() []Pluginer

func (*AppStruct) GetRole

func (r *AppStruct) GetRole(name string) *acl.Role

func (*AppStruct) GetRolePermission

func (r *AppStruct) GetRolePermission(name string, permission string) bool

func (*AppStruct) GetRoles

func (r *AppStruct) GetRoles() map[string]*acl.Role

func (*AppStruct) GetRouter

func (r *AppStruct) GetRouter() *echo.Echo

func (*AppStruct) GetRouterGroup

func (r *AppStruct) GetRouterGroup(name string) *echo.Group

func (*AppStruct) GetSanitizer

func (app *AppStruct) GetSanitizer() *bluemonday.Policy

func (*AppStruct) GetTemplates

func (r *AppStruct) GetTemplates() *template.Template

func (*AppStruct) GetTheme

func (r *AppStruct) GetTheme() string

Get default app theme

func (*AppStruct) InitDatabase

func (r *AppStruct) InitDatabase(name, engine string, isDefault bool) error

func (*AppStruct) LoadTemplates

func (r *AppStruct) LoadTemplates() error

func (*AppStruct) Migrate

func (r *AppStruct) Migrate() error

Run migrations

func (*AppStruct) NewRequestContext

func (app *AppStruct) NewRequestContext(opts *RequestContextOpts) *RequestContext

func (*AppStruct) RegisterPlugin

func (r *AppStruct) RegisterPlugin(p Pluginer)

func (*AppStruct) RenderTemplate

func (app *AppStruct) RenderTemplate(wr io.Writer, name string, data interface{}) error

RenderTemplate - Render template with default app theme

func (*AppStruct) SetClock

func (app *AppStruct) SetClock(clock clock.Clock) error

func (*AppStruct) SetContentTypes added in v1.0.1

func (app *AppStruct) SetContentTypes(contentTypes []string) error

func (*AppStruct) SetDB

func (r *AppStruct) SetDB(db *gorm.DB) error

func (*AppStruct) SetLayout

func (r *AppStruct) SetLayout(layout string) error

Set default app Layout

func (*AppStruct) SetModel

func (r *AppStruct) SetModel(name string, f interface{})

func (*AppStruct) SetPlugin

func (r *AppStruct) SetPlugin(name string, plugin Pluginer) error

func (*AppStruct) SetResource

func (r *AppStruct) SetResource(name string, httpController HTTPController, routerGroup *echo.Group) error

Set Resource CRUD. Now we only supports HTTP Resources / Ex Rest

func (*AppStruct) SetRole

func (r *AppStruct) SetRole(name string, role acl.Role) error

func (*AppStruct) SetRolePermission

func (r *AppStruct) SetRolePermission(name string, permission string, hasAccess bool) error

func (*AppStruct) SetRouterGroup

func (r *AppStruct) SetRouterGroup(name, path string) *echo.Group

func (*AppStruct) SetSanitizer

func (app *AppStruct) SetSanitizer(sanitizer *bluemonday.Policy) error

func (*AppStruct) SetTemplateFunction

func (r *AppStruct) SetTemplateFunction(name string, f interface{})

func (*AppStruct) SetTheme

func (r *AppStruct) SetTheme(theme string) error

Set default app theme

func (*AppStruct) StartHTTPServer

func (r *AppStruct) StartHTTPServer() error

type BaseErrorResponse

type BaseErrorResponse struct {
	Messages []BaseErrorResponseMessage `json:"messages"`
}

func ParseEchoHTTPErrorToResponse added in v1.1.4

func ParseEchoHTTPErrorToResponse(ctx *RequestContext, he *echo.HTTPError) *BaseErrorResponse

func ParseHTTPErrorToResponse added in v1.1.4

func ParseHTTPErrorToResponse(ctx *RequestContext, he HTTPErrorInterface) *BaseErrorResponse

type BaseErrorResponseMessage

type BaseErrorResponseMessage struct {
	Status  string `json:"status"`
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type BaseListReponse

type BaseListReponse struct {
	Meta BaseMetaResponse `json:"meta"`
}

type BaseMetaResponse

type BaseMetaResponse struct {
	Count int64 `json:"count"`
}

type ContentDates

type ContentDates interface {
	GetTeaserDatesHTML(separator string) template.HTML
}

type Context

type Context interface {
	Get(key string) interface{}
	Set(key string, val interface{})
}

type CustomBinder

type CustomBinder struct{}

func (*CustomBinder) Bind

func (cb *CustomBinder) Bind(i interface{}, c echo.Context) (err error)

type DefaultResponse

type DefaultResponse struct {
	Data   any
	Status int
}

func (*DefaultResponse) GetData

func (r *DefaultResponse) GetData() any

func (*DefaultResponse) GetStatusCode

func (r *DefaultResponse) GetStatusCode() int

type EmptyResponse

type EmptyResponse struct{}

type HTTPController

type HTTPController interface {
	Query(c echo.Context) error
	Create(c echo.Context) error
	Count(c echo.Context) error
	FindOne(c echo.Context) error
	Update(c echo.Context) error
	Delete(c echo.Context) error
}

type HTTPError

type HTTPError struct {
	Code     int         `json:"code"`
	Message  interface{} `json:"message"`
	Internal error       `json:"-"` // Stores the error returned by an external dependency
}

HTTPError implements HTTP Error interface, default error object

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error makes it compatible with `error` interface.

func (*HTTPError) GetCode

func (e *HTTPError) GetCode() int

func (*HTTPError) GetInternal

func (e *HTTPError) GetInternal() error

func (*HTTPError) GetMessage

func (e *HTTPError) GetMessage() interface{}

func (*HTTPError) SetCode

func (e *HTTPError) SetCode(code int) error

func (*HTTPError) SetInternal

func (e *HTTPError) SetInternal(internal error) error

func (*HTTPError) SetMessage

func (e *HTTPError) SetMessage(message interface{}) error

type HTTPErrorInterface

type HTTPErrorInterface interface {
	Error() string
	GetCode() int
	SetCode(code int) error
	GetMessage() interface{}
	SetMessage(message interface{}) error
}

type HTTPResource

type HTTPResource struct {
	Name       string
	Controller *HTTPController
}

type Migration added in v1.1.0

type Migration struct {
	Name string
	Up   func(app App) error
	Down func(app App) error
}

type MigrationEngine added in v1.1.0

type MigrationEngine struct {
	App App
}

func NewMigrationEngine added in v1.1.0

func NewMigrationEngine(opts *NewMigrationEngineOpts) *MigrationEngine

func (*MigrationEngine) FindAllMigrations added in v1.1.0

func (m *MigrationEngine) FindAllMigrations() ([]*MigrationModel, error)

func (*MigrationEngine) FindAllMigrationsByPlugin added in v1.1.0

func (m *MigrationEngine) FindAllMigrationsByPlugin() (map[string]*MigrationModel, error)

func (*MigrationEngine) GetPluginMigrations added in v1.1.0

func (m *MigrationEngine) GetPluginMigrations() ([]*Migration, error)

func (*MigrationEngine) SetupMigrationEngine added in v1.1.0

func (m *MigrationEngine) SetupMigrationEngine() error

type MigrationModel added in v1.1.0

type MigrationModel struct {
	PluginName      string    `gorm:"column:plugin_name;primaryKey;type:varchar(200)"`
	Version         int       `gorm:"column:version"`
	LastUpgradeName string    `gorm:"column:last_upgrade_name"`
	CreatedAt       time.Time `gorm:"column:created_at;default:NOW();not null"`
	UpdatedAt       time.Time `gorm:"column:updated_at;default:NOW();not null"`
	LastError       string    `gorm:"column:last_error;type:TEXT"`
}

func (*MigrationModel) Save added in v1.1.0

func (m *MigrationModel) Save(app App) error

func (*MigrationModel) TableName added in v1.1.0

func (m *MigrationModel) TableName() string

type NewMigrationEngineOpts added in v1.1.0

type NewMigrationEngineOpts struct {
	App App
}

type Plugin

type Plugin struct {
	Name string
}

Core plugin

func (*Plugin) BindMiddlewares

func (p *Plugin) BindMiddlewares(a App) error

func (*Plugin) GetMigrations added in v1.1.0

func (p *Plugin) GetMigrations() []*Migration

func (*Plugin) GetName

func (p *Plugin) GetName() string

func (*Plugin) Init

func (p *Plugin) Init(a App) error

func (*Plugin) SetTemplateFuncMap

func (p *Plugin) SetTemplateFuncMap(app App) error

type PluginManager

type PluginManager interface {
	GetRouter(name string) *echo.Group
	SetRouter(name string) *echo.Group
	GetAPIRouter(name string) *echo.Group
}

type Pluginer

type Pluginer interface {
	Init(app App) error
	GetName() string
	GetMigrations() []*Migration
}

type RequestContext

type RequestContext struct {
	App App

	Protocol  string
	Domain    string
	AppOrigin string
	Title     string

	IsAuthenticated   bool
	AuthenticatedUser UserInterface
	// authenticated user role name list
	Roles []string

	Session SessionData

	Widgets   map[string]map[string]string
	Theme     string
	Layout    string
	BodyClass []string
	Content   template.HTML
	Query     query_parser_to_db.QueryInterface
	Pager     *pagination.Pager

	ENV string
	// contains filtered or unexported fields
}

func NewBotContext

func NewBotContext(app App) (*RequestContext, error)

NewBotContext - Create a new request context for non http calls and testing

func NewRequestContext

func NewRequestContext(opts *RequestContextOpts) *RequestContext

func (*RequestContext) AddBodyClass

func (r *RequestContext) AddBodyClass(class string)

Add a body class string checking if is unique

func (*RequestContext) AddResponseMessage added in v1.0.2

func (r *RequestContext) AddResponseMessage(msg *ResponseMessage) error

func (*RequestContext) Attachment

func (c *RequestContext) Attachment(file string, name string) error

Attachment sends a response as attachment, prompting client to save the file.

func (*RequestContext) Bind

func (c *RequestContext) Bind(i interface{}) error

Bind binds the request body into provided type `i`. The default binder does it based on Content-Type header.

func (*RequestContext) Blob

func (c *RequestContext) Blob(code int, contentType string, b []byte) error

Blob sends a blob response with status code and content type.

func (*RequestContext) Can

func (r *RequestContext) Can(permission string) bool

func (*RequestContext) Cookie

func (c *RequestContext) Cookie(name string) (*http.Cookie, error)

Cookie returns the named cookie provided in the request.

func (*RequestContext) Cookies

func (c *RequestContext) Cookies() []*http.Cookie

Cookies returns the HTTP cookies sent with the request.

func (*RequestContext) Echo

func (c *RequestContext) Echo() *echo.Echo

Echo returns the `Echo` instance.

func (*RequestContext) Error

func (c *RequestContext) Error(err error)

Error invokes the registered HTTP error handler. Generally used by middleware.

func (*RequestContext) File

func (c *RequestContext) File(file string) error

File sends a response with the content of the file.

func (*RequestContext) FormFile

func (c *RequestContext) FormFile(name string) (*multipart.FileHeader, error)

FormFile returns the multipart form file for the provided name.

func (*RequestContext) FormParams

func (c *RequestContext) FormParams() (url.Values, error)

FormParams returns the form parameters as `url.Values`.

func (*RequestContext) FormValue

func (c *RequestContext) FormValue(name string) string

FormValue returns the form field value for the provided name.

func (*RequestContext) Get

func (r *RequestContext) Get(name string) interface{}

func (*RequestContext) GetAuthenticatedRoles

func (r *RequestContext) GetAuthenticatedRoles() *[]string

func (*RequestContext) GetBodyClassText

func (r *RequestContext) GetBodyClassText() string

Get body class as string,

func (*RequestContext) GetBool

func (r *RequestContext) GetBool(name string) bool

Get value from echo context data in boolean format

func (*RequestContext) GetLimit

func (r *RequestContext) GetLimit() int

func (*RequestContext) GetOffset

func (r *RequestContext) GetOffset() int

func (*RequestContext) GetResponseContentType

func (r *RequestContext) GetResponseContentType() string

Get selected response type

func (*RequestContext) GetResponseMessages added in v1.0.2

func (r *RequestContext) GetResponseMessages() []*ResponseMessage

func (*RequestContext) GetString

func (r *RequestContext) GetString(name string) string

func (*RequestContext) GetStringMap

func (r *RequestContext) GetStringMap(name string) []string

Get data in string map format ([]string) from echo context data

func (*RequestContext) GetTemplateHTML

func (r *RequestContext) GetTemplateHTML(name string) template.HTML

func (*RequestContext) HTML

func (c *RequestContext) HTML(code int, html string) error

HTML sends an HTTP response with status code.

func (*RequestContext) HTMLBlob

func (c *RequestContext) HTMLBlob(code int, b []byte) error

HTMLBlob sends an HTTP blob response with status code.

func (*RequestContext) Handler

func (c *RequestContext) Handler() echo.HandlerFunc

Handler returns the matched handler by router.

func (*RequestContext) Inline

func (c *RequestContext) Inline(file string, name string) error

Inline sends a response as inline, opening the file in the browser.

func (*RequestContext) IsTLS

func (c *RequestContext) IsTLS() bool

IsTLS returns true if HTTP connection is TLS otherwise false.

func (*RequestContext) IsWebSocket

func (c *RequestContext) IsWebSocket() bool

IsWebSocket returns true if HTTP connection is WebSocket otherwise false.

func (*RequestContext) JSON

func (c *RequestContext) JSON(code int, i interface{}) error

JSON sends a JSON response with status code.

func (*RequestContext) JSONBlob

func (c *RequestContext) JSONBlob(code int, b []byte) error

JSONBlob sends a JSON blob response with status code.

func (*RequestContext) JSONP

func (c *RequestContext) JSONP(code int, callback string, i interface{}) error

JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.

func (*RequestContext) JSONPBlob

func (c *RequestContext) JSONPBlob(code int, callback string, b []byte) error

JSONPBlob sends a JSONP blob response with status code. It uses `callback` to construct the JSONP payload.

func (*RequestContext) JSONPretty

func (c *RequestContext) JSONPretty(code int, i interface{}, indent string) error

JSONPretty sends a pretty-print JSON with status code.

func (*RequestContext) Logger

func (c *RequestContext) Logger() echo.Logger

Logger returns the `Logger` instance.

func (*RequestContext) MultipartForm

func (c *RequestContext) MultipartForm() (*multipart.Form, error)

MultipartForm returns the multipart form.

func (*RequestContext) NoContent

func (c *RequestContext) NoContent(code int) error

NoContent sends a response with no body and a status code.

func (*RequestContext) Param

func (c *RequestContext) Param(name string) string

Param returns path parameter by name.

func (*RequestContext) ParamNames

func (c *RequestContext) ParamNames() []string

ParamNames returns path parameter names.

func (*RequestContext) ParamValues

func (c *RequestContext) ParamValues() []string

ParamValues returns path parameter values.

func (*RequestContext) ParseQueryFromReq

func (r *RequestContext) ParseQueryFromReq(c echo.Context) error

func (*RequestContext) Partial

func (r *RequestContext) Partial(name string, data interface{}) template.HTML

Partial - Include and render one template inside other

func (*RequestContext) Path

func (c *RequestContext) Path() string

Path returns the registered path for the handler.

func (*RequestContext) QueryParam

func (c *RequestContext) QueryParam(name string) string

QueryParam returns the query param for the provided name.

func (*RequestContext) QueryParams

func (c *RequestContext) QueryParams() url.Values

QueryParams returns the query parameters as `url.Values`.

func (*RequestContext) QueryString

func (c *RequestContext) QueryString() string

QueryString returns the URL query string.

func (*RequestContext) RealIP

func (c *RequestContext) RealIP() string

RealIP returns the client's network address based on `X-Forwarded-For` or `X-Real-IP` request header. The behavior can be configured using `Echo#IPExtractor`.

func (*RequestContext) Redirect

func (c *RequestContext) Redirect(code int, url string) error

Redirect redirects the request to a provided URL with status code.

func (*RequestContext) RemoveBodyClass

func (r *RequestContext) RemoveBodyClass(class string)

Remove a body class string checking if is unique

func (*RequestContext) Render

func (c *RequestContext) Render(code int, name string, data interface{}) error

Render renders a template with data and sends a text/html response with status code. Renderer must be registered using `Echo.Renderer`.

func (*RequestContext) RenderPagination

func (r *RequestContext) RenderPagination(name string) string

func (*RequestContext) RenderTemplate

func (r *RequestContext) RenderTemplate(wr io.Writer, name string, data interface{}) error

Render one template, with support for themes

func (*RequestContext) Request

func (c *RequestContext) Request() *http.Request

Request returns `*http.Request`.

func (*RequestContext) Reset

func (c *RequestContext) Reset(r *http.Request, w http.ResponseWriter)

Reset resets the context after request completes. It must be called along with `Echo#AcquireContext()` and `Echo#ReleaseContext()`. See `Echo#ServeHTTP()`

func (*RequestContext) Response

func (c *RequestContext) Response() *echo.Response

Response returns `*Response`.

func (*RequestContext) Scheme

func (c *RequestContext) Scheme() string

Scheme returns the HTTP protocol scheme, `http` or `https`.

func (*RequestContext) Set

func (r *RequestContext) Set(name string, value interface{})

func (*RequestContext) SetAuthenticatedUser

func (r *RequestContext) SetAuthenticatedUser(user UserInterface)

func (*RequestContext) SetAuthenticatedUserAndFillRoles

func (r *RequestContext) SetAuthenticatedUserAndFillRoles(user UserInterface)

func (*RequestContext) SetCookie

func (c *RequestContext) SetCookie(cookie *http.Cookie)

SetCookie adds a `Set-Cookie` header in HTTP response.

func (*RequestContext) SetHandler

func (c *RequestContext) SetHandler(h echo.HandlerFunc)

SetHandler sets the matched handler by router.

func (*RequestContext) SetLogger

func (c *RequestContext) SetLogger(l echo.Logger)

Set the logger

func (*RequestContext) SetParamNames

func (c *RequestContext) SetParamNames(names ...string)

SetParamNames sets path parameter names.

func (*RequestContext) SetParamValues

func (c *RequestContext) SetParamValues(values ...string)

SetParamValues sets path parameter values.

func (*RequestContext) SetPath

func (c *RequestContext) SetPath(p string)

SetPath sets the registered path for the handler.

func (*RequestContext) SetRequest

func (c *RequestContext) SetRequest(r *http.Request)

SetRequest sets `*http.Request`.

func (*RequestContext) SetResponse

func (c *RequestContext) SetResponse(r *echo.Response)

SetResponse sets `*Response`.

func (*RequestContext) SetResponseContentType

func (r *RequestContext) SetResponseContentType(v string) error

Set response type, returns error if the type is invalid

func (*RequestContext) Stream

func (c *RequestContext) Stream(code int, contentType string, r io.Reader) error

Stream sends a streaming response with status code and content type.

func (*RequestContext) String

func (c *RequestContext) String(code int, s string) error

String sends a string response with status code.

func (*RequestContext) Validate

func (c *RequestContext) Validate(i interface{}) error

Validate validates provided `i`. It is usually called after `Context#Bind()`. Validator must be registered using `Echo#Validator`.

func (*RequestContext) XML

func (c *RequestContext) XML(code int, i interface{}) error

XML sends an XML response with status code.

func (*RequestContext) XMLBlob

func (c *RequestContext) XMLBlob(code int, b []byte) error

XMLBlob sends an XML blob response with status code.

func (*RequestContext) XMLPretty

func (c *RequestContext) XMLPretty(code int, i interface{}, indent string) error

XMLPretty sends a pretty-print XML with status code.

type RequestContextOpts

type RequestContextOpts struct {
	App         App
	EchoContext echo.Context
}

type Response

type Response interface {
	GetData() any
	GetStatusCode() int
}

func Redirect

func Redirect(c echo.Context, code int, url string) (Response, error)

type ResponseMessage added in v1.0.2

type ResponseMessage struct {
	Message string `json:"message"`
	Type    string `json:"type"`
}

type ResponseMessageTPLCtx added in v1.0.2

type ResponseMessageTPLCtx struct {
	Ctx     *RequestContext
	Message *ResponseMessage
}

type ResponseMessagesTPLCtx added in v1.0.2

type ResponseMessagesTPLCtx struct {
	Ctx     *RequestContext
	Content string
}

type Route

type Route struct {
	Method     string
	Prefix     string
	Path       string
	Action     Action
	Permission string
	AcceptOnly string
	Template   string
	Layout     string
	Theme      string
	Model      interface{}
}

type SessionData

type SessionData struct {
	UserID string
}

type TemplateCTX

type TemplateCTX struct {
	EchoContext echo.Context
	Ctx         interface{}
	Record      interface{}
	Records     interface{}
}

type TemplateRenderer

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

func (*TemplateRenderer) Render

func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error

type UserInterface

type UserInterface interface {
	// getters:
	GetID() string
	SetID(id string) error
	GetRoles() []string
	SetRoles(v []string) error
	AddRole(role string) error
	RemoveRole(role string) error
	GetEmail() string
	SetEmail(v string) error
	GetUsername() string
	SetUsername(v string) error
	GetDisplayName() string
	SetDisplayName(v string) error
	GetFullName() string
	SetFullName(v string) error
	GetLanguage() string
	SetLanguage(v string) error
	IsActive() bool
	SetActive(blocked bool) error
	IsBlocked() bool
	SetBlocked(blocked bool) error
	// FillById
	FillById(ID string) error
}

type ValidationFieldError

type ValidationFieldError struct {
	Field   string `json:"field"`
	Tag     string `json:"tag"`
	Value   string `json:"value"`
	Message string `json:"message"`
}

type ValidationResponse

type ValidationResponse struct {
	Errors []*ValidationFieldError `json:"errors"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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