Documentation
¶
Index ¶
- Constants
- Variables
- type App
- func (app *App) Close()
- func (app *App) Delete(pattern string, hf HandleFunc, opts ...RoutingOption)
- func (app *App) Get(pattern string, hf HandleFunc, opts ...RoutingOption)
- func (app *App) Group(prefix string) Router
- func (app *App) HandleFile(name string, v *FileViewer)
- func (app *App) HandleFunc(pattern string, hf HandleFunc, opts ...RoutingOption)
- func (app *App) HandlePage(pattern string, viewName string, v Viewer)
- func (app *App) Next(hf HandleFunc) HandleFunc
- func (app *App) Post(pattern string, hf HandleFunc, opts ...RoutingOption)
- func (app *App) Put(pattern string, hf HandleFunc, opts ...RoutingOption)
- func (app *App) Start()
- func (app *App) Use(middleware ...Middleware)
- type BufferPool
- type Context
- func (c *Context) Accept() (types []string)
- func (c *Context) AcceptLanguage() (languages []string)
- func (c *Context) Get(key string) any
- func (c *Context) Redirect(url string, statusCode ...int)
- func (c *Context) Request() *http.Request
- func (c *Context) RequestReferer() *url.URL
- func (c *Context) Set(key string, value any)
- func (c *Context) View(items ...any) error
- func (c *Context) WriteHeader(key string, value string)
- func (c *Context) WriteStatus(code int)
- func (c *Context) Writer() http.ResponseWriter
- type FileViewer
- type HandleFunc
- type Handler
- type HtmlTemplate
- type HtmlViewEngine
- type HtmlViewer
- type Interceptor
- type JsonViewer
- type Middleware
- type Option
- type Router
- type Routing
- type RoutingOption
- type RoutingOptions
- type StaticViewEngine
- type TEntity
- type Validator
- type ViewEngine
- type Viewer
Constants ¶
const ( )
Variables ¶
var (
ErrCancelled = errors.New("xun: request_cancelled")
)
FuncMap is a map of functions that are available to templates.
Functions ¶
This section is empty.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the main struct of the framework.
It is used to register routes, middleware, and view engines.
The application instance is initialized with a new http.ServeMux, and a handler that serves files from the current working directory is registered.
The application instance is ready to be used with the standard http.Server type.
func New ¶
New allocates an App instance and loads all view engines.
All view engines are loaded from root directory of given fs.FS. If watch is true, it will watch all file changes and reload all view engines if any files are changed. If watch is false, it won't watch any file changes.
func (*App) Delete ¶
func (app *App) Delete(pattern string, hf HandleFunc, opts ...RoutingOption)
Delete registers a route handler for the given HTTP DELETE request pattern.
func (*App) Get ¶
func (app *App) Get(pattern string, hf HandleFunc, opts ...RoutingOption)
Get registers a route handler for the given HTTP GET request pattern.
func (*App) Group ¶
Middleware is a function that takes a HandleFunc and returns a HandleFunc. Middleware functions are useful for creating reusable pieces of code that can be composed together to create complex behavior. For example, a middleware function might be used to log each request, or to check if a user is authenticated before allowing access to a page.
func (*App) HandleFile ¶
func (app *App) HandleFile(name string, v *FileViewer)
HandleFile registers a route handler for serving a file.
This function associates a FileViewer with a given file name and registers the route in the application's routing table. If a route with the same pattern already exists, it returns immediately without making any changes.
func (*App) HandleFunc ¶
func (app *App) HandleFunc(pattern string, hf HandleFunc, opts ...RoutingOption)
HandleFunc registers a route handler for the given HTTP request pattern.
The pattern is expected to be in the format "METHOD PATTERN", where METHOD is the HTTP method (e.g. "GET", "POST", etc.) and PATTERN is the URL path pattern.
The opts parameter is a list of RoutingOption functions that can be used to customize the route. See the RoutingOption type for more information.
func (*App) HandlePage ¶
HandlePage registers a route handler for a page view.
This function associates a Viewer with a given route pattern and registers the route in the application's routing table. If a route with the same pattern already exists, it updates the existing route with the new Viewer.
func (*App) Next ¶
func (app *App) Next(hf HandleFunc) HandleFunc
func (*App) Post ¶
func (app *App) Post(pattern string, hf HandleFunc, opts ...RoutingOption)
Post registers a route handler for the given HTTP POST request pattern.
func (*App) Put ¶
func (app *App) Put(pattern string, hf HandleFunc, opts ...RoutingOption)
Put registers a route handler for the given HTTP PUT request pattern.
func (*App) Use ¶
func (app *App) Use(middleware ...Middleware)
Use registers one or more Middleware functions to be executed before any route handler. Middleware functions are useful for creating reusable pieces of code that can be composed together to create complex behavior. For example, a middleware function might be used to log each request, or to check if a user is authenticated before allowing access to a page.
The order of middleware functions matters. The first middleware function that is registered will be executed first, and the last middleware function that is registered will be executed last.
Middleware functions are executed in the order they are registered.
type BufferPool ¶
type BufferPool struct {
// contains filtered or unexported fields
}
BufferPool is a pool of *bytes.Buffer for reuse to reduce memory alloc.
var BufPool *BufferPool
BufPool is a pool of *bytes.Buffer for reuse to reduce memory alloc.
It is used by the HtmlViewer to render the template. The pool is created with a size of 100, but you can change it by setting the BufPool variable before creating any HtmlViewer instances.
func NewBufferPool ¶
func NewBufferPool(size int) (bp *BufferPool)
NewBufferPool returns a new BufferPool with the given size.
The size determines how many buffers can be stored in the pool. If the pool is full and a new buffer is requested, a new buffer will be created.
func (*BufferPool) Get ¶
func (bp *BufferPool) Get() (b *bytes.Buffer)
Get retrieves a buffer from the pool or creates a new one if the pool is empty.
If a buffer is available in the pool, it is returned for reuse, reducing memory allocations. If the pool is empty, a new buffer is created and returned.
func (*BufferPool) Put ¶
func (bp *BufferPool) Put(b *bytes.Buffer)
Put returns a buffer to the pool for reuse or discards if the pool is full.
This function resets the buffer to clear any existing data before returning it to the pool. If the pool is already full, the buffer is discarded.
type Context ¶
type Context struct {
Routing Routing
// contains filtered or unexported fields
}
Context is the primary structure for handling HTTP requests. It encapsulates the request, response, routing information, and application context. It offers various methods to work with request data, manipulate responses, and manage routing.
func (*Context) Accept ¶
Accept returns a slice of strings representing the media types that the client accepts, in order of preference. The media types are normalized to lowercase and whitespace is trimmed.
func (*Context) AcceptLanguage ¶
AcceptLanguage returns a slice of strings representing the languages that the client accepts, in order of preference. The languages are normalized to lowercase and whitespace is trimmed.
func (*Context) Get ¶
Get retrieves a value from the context's values map by key. If the values map is nil or the key does not exist, it returns nil.
func (*Context) Redirect ¶
Redirect redirects the user to the given url. It uses the given status code. If the status code is not provided, it uses http.StatusFound (302).
func (*Context) Request ¶
Request returns the HTTP request associated with the current context. It allows access to the request data and headers.
func (*Context) RequestReferer ¶
RequestReferer returns the referer of the request.
func (*Context) Set ¶
Set assigns a value to the specified key in the context's values map. If the values map is nil, it initializes a new map.
func (*Context) View ¶
View renders a view with the given data and optional view name. items should have 1 or 2 inputs. first one is data, second one is view name. If a view name is provided, it attempts to fetch a viewer by name and uses it to render the view. If no view name is provided, it uses the default viewer. The data parameter is any type and will be passed to the viewer's Render method.
func (*Context) WriteHeader ¶
WriteHeader sets a response header.
If the value is an empty string, the header will be deleted.
func (*Context) WriteStatus ¶
WriteStatus sets the HTTP status code for the response. It is used to return error or success status codes to the client. The status code will be sent to the client only once the response body is closed. If a status code is not set, the default status code is 200 (OK).
func (*Context) Writer ¶
func (c *Context) Writer() http.ResponseWriter
Writer returns the http.ResponseWriter associated with the current context. It allows writing to the HTTP response body and setting response headers.
type FileViewer ¶
type FileViewer struct {
// contains filtered or unexported fields
}
FileViewer is a viewer that serves a file from a file system.
You can use it to serve a file from a file system, or to serve a file from a zip file.
The file system is specified by the `fsys` field, and the path is specified by the `path` field.
For example, to serve a file from the current working directory, you can use the following code:
viewer := &FileViewer{
fsys: os.DirFS("."),
path: "example.txt",
}
app.HandleFile("example.txt", viewer)
func (*FileViewer) MimeType ¶
func (*FileViewer) MimeType() string
MimeType returns the MIME type of the file.
The MIME type is determined by the file extension of the file.
func (*FileViewer) Render ¶
func (v *FileViewer) Render(w http.ResponseWriter, r *http.Request, data any) error
Render serves a file from the file system using the FileViewer. It writes the file to the http.ResponseWriter.
type HandleFunc ¶
type Handler ¶
type Handler struct {
Viewers []Viewer
Pattern string // original string
Method string
Host string
}
Handler represents an HTTP handler.
type HtmlTemplate ¶
type HtmlTemplate struct {
// contains filtered or unexported fields
}
HtmlTemplate is a template that is loaded from a file system.
func NewHtmlTemplate ¶
func NewHtmlTemplate(name, path string) *HtmlTemplate
NewHtmlTemplate creates a new HtmlTemplate with the given name and path.
func (*HtmlTemplate) Execute ¶
func (t *HtmlTemplate) Execute(wr io.Writer, data any) error
Execute renders the template with the given data and writes the result to the provided writer.
If the template has a layout, it uses the layout to render the data. Otherwise, it renders the data using the template itself.
func (*HtmlTemplate) Load ¶
func (t *HtmlTemplate) Load(fsys fs.FS, templates map[string]*HtmlTemplate) error
Load loads the template from the given file system.
It parses the file, and determines the dependencies of the template. The dependencies are stored in the `dependencies` field.
func (*HtmlTemplate) Reload ¶
func (t *HtmlTemplate) Reload(fsys fs.FS, templates map[string]*HtmlTemplate) error
Reload reloads the template and all its dependents from the given file system.
It first reloads the current template and then recursively reloads all its dependents. If a dependency does not exist, it is removed from the list of dependents.
type HtmlViewEngine ¶
type HtmlViewEngine struct {
// contains filtered or unexported fields
}
HtmlViewEngine is a view engine that loads templates from a file system.
It supports 2 types of templates:
- Components: These are templates that are loaded from the "components" directory.
- Pages: These are templates that are loaded from the "layouts/views/pages/" directory.
Components are used to build up larger templates, while pages are used to render the final HTML that is sent to the client.
func (*HtmlViewEngine) FileChanged ¶
FileChanged is called when a file has been changed.
It is used to reload templates when they have been changed.
type HtmlViewer ¶
type HtmlViewer struct {
// contains filtered or unexported fields
}
HtmlViewer is a viewer that renders a html template.
It uses the `HtmlTemplate` type to render a template. The template is loaded from the file system when the viewer is created. The `Render` method renders the template with the given data and writes the result to the http.ResponseWriter.
func (*HtmlViewer) MimeType ¶
func (*HtmlViewer) MimeType() string
MimeType returns the MIME type of the HTML content.
This implementation returns "text/html".
func (*HtmlViewer) Render ¶
func (v *HtmlViewer) Render(w http.ResponseWriter, r *http.Request, data any) error
Render renders the template with the given data and writes the result to the http.ResponseWriter.
This implementation uses the `HtmlTemplate.Execute` method to render the template. The rendered result is written to the http.ResponseWriter.
type Interceptor ¶
type Interceptor interface {
// RequestReferer returns the referer of the request.
RequestReferer(c *Context) string
// Redirect sends an HTTP redirect to the client.
Redirect(c *Context, url string, statusCode ...int) bool
}
Interceptor is an interface that provides methods to intercept requests and response.
type JsonViewer ¶
type JsonViewer struct {
}
JsonViewer is a viewer that writes the given data as JSON to the http.ResponseWriter.
It sets the Content-Type header to "application/json".
func (*JsonViewer) MimeType ¶
func (*JsonViewer) MimeType() string
MimeType returns the MIME type of the JSON content.
It returns "application/json".
func (*JsonViewer) Render ¶
func (j *JsonViewer) Render(w http.ResponseWriter, r *http.Request, data any) error
Render renders the given data as JSON to the http.ResponseWriter.
It sets the Content-Type header to "application/json".
type Middleware ¶
type Middleware func(next HandleFunc) HandleFunc
type Option ¶
type Option func(*App)
Option is a function that takes a pointer to an App and modifies it. It is used to configure an App when calling the New function.
func WithInterceptor ¶
func WithInterceptor(i Interceptor) Option
func WithLogger ¶
WithLogger sets the logger for the App. If not set, it will use slog.Default()
func WithMux ¶
WithMux sets the http.ServeMux for the App. If not set, it will use http.DefaultServeMux.
func WithViewEngines ¶
func WithViewEngines(ve ...ViewEngine) Option
WithViewEngines sets the ViewEngines for the App. If not set, it will use the default ViewEngines.
func WithViewer ¶
WithViewer sets the default Viewer for the App. If not set, it will use JsonViewer.
type Router ¶
type Router interface {
Get(pattern string, h HandleFunc, opts ...RoutingOption)
Post(pattern string, h HandleFunc, opts ...RoutingOption)
Put(pattern string, h HandleFunc, opts ...RoutingOption)
Delete(pattern string, h HandleFunc, opts ...RoutingOption)
HandleFunc(pattern string, h HandleFunc, opts ...RoutingOption)
Use(middlewares ...Middleware)
}
Router is the interface that wraps the minimum set of methods required for an effective router, namely methods for adding routes for different HTTP methods, a method for adding middleware, and a method for adding the router to the main app.
type Routing ¶
type Routing struct {
Pattern string
Handle HandleFunc
Options *RoutingOptions
Viewers map[string]Viewer
// contains filtered or unexported fields
}
Routing represents a single route in the router.
type RoutingOption ¶
type RoutingOption func(*RoutingOptions)
RoutingOption is a function that takes a pointer to RoutingOptions and modifies it. It is used to customize the behavior of the router when adding routes.
func WithMetadata ¶
func WithMetadata(key string, value any) RoutingOption
WithMetadata adds a key-value pair to the routing metadata. It creates a new map if the metadata map is nil.
func WithNavigation ¶
func WithNavigation(name, icon, access string) RoutingOption
WithNavigation adds navigation-related metadata to the routing options. It sets the name, icon, and access level for the navigation element.
type RoutingOptions ¶
type RoutingOptions struct {
// contains filtered or unexported fields
}
RoutingOptions holds metadata and a viewer for routing configuration.
func (*RoutingOptions) Get ¶
func (ro *RoutingOptions) Get(name string) any
Get returns the value associated with the given name from the routing metadata. If the name does not exist, it returns nil.
func (*RoutingOptions) GetInt ¶
func (ro *RoutingOptions) GetInt(name string) int
GetInt returns the value associated with the given name from the routing metadata as an integer. If the name does not exist, it returns 0.
func (*RoutingOptions) GetString ¶
func (ro *RoutingOptions) GetString(name string) string
GetString returns the value associated with the given name from the routing metadata as a string. If the name does not exist, it returns an empty string.
type StaticViewEngine ¶
type StaticViewEngine struct {
}
StaticViewEngine is a view engine that serves static files from a file system.
func (*StaticViewEngine) FileChanged ¶
FileChanged handles file changes for the given file system and updates the application accordingly. It is called by the watcher when a file is changed.
If the file changed is a Create event and the path is in the "public" directory, it will be registered with the application.
If the file changed is a Write/Remove event and the path is in the "public" directory, nothing will be done.
func (*StaticViewEngine) Load ¶
func (ve *StaticViewEngine) Load(fsys fs.FS, app *App) error
Load loads all static files from the given file system and registers them with the application.
It scans the "public" directory in the given file system and registers each file with the application. It also handles file changes for the "public" directory and updates the application accordingly.
type TEntity ¶
TEntity is a struct that contains the data and errors.
It is used by the Bind functions to return the data and errors.
func BindForm ¶
BindForm binds the request body to the given struct.
It supports application/x-www-form-urlencoded, multipart/form-data.
If the request body is empty or the decoding fails, it returns an error.
func BindJson ¶
BindJson binds the JSON request body to the given struct.
It attempts to decode the JSON body into the specified type.
If the decoding fails, it returns an error.
type Validator ¶
type Validator struct {
*validator.Validate
Translator ut.Translator
}
Validator validates struct and field values.
It uses the specified languages to find an appropriate validator and translates the error messages.
func AddValidator ¶
func AddValidator(trans ut.Translator, register func(v *validator.Validate, trans ut.Translator) (err error)) *Validator
AddValidator adds a new validator and translator to the map.
It also registers the translations for the default locale.
type ViewEngine ¶
type ViewEngine interface {
Load(fsys fs.FS, app *App) error
FileChanged(fsys fs.FS, app *App, event fsnotify.Event) error
}
ViewEngine is the interface that wraps the minimum set of methods required for an effective view engine, namely methods for loading templates from a file system and reloading templates when the file system changes.