### Install BunRouter Go Package Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter This command installs the BunRouter Go package using the go get command. It's a prerequisite for using BunRouter in your Go projects. ```bash go get github.com/uptrace/bunrouter ``` -------------------------------- ### Router Compatibility Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Information on how to get a compatibility router instance. ```APIDOC ## Router Compatibility ### Description Provides a compatibility layer for routing. ### Methods #### `Compat() *CompatRouter` Returns a new `CompatRouter` instance that wraps the current router. ``` -------------------------------- ### BunRouter Basic HTTP Server Example Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter This Go code demonstrates a basic HTTP server using BunRouter. It sets up a root handler for the index page and defines a group of API routes with different parameter types. The server listens on port 9999. ```go package main import ( hml/template "log" "net/http" "github.com/uptrace/bunrouter" "github.com/uptrace/bunrouter/extra/reqlog" ) func main() { router := bunrouter.New( bunrouter.Use(reqlog.NewMiddleware()), ) router.GET("/", indexHandler) router.WithGroup("/api", func(g *bunrouter.Group) { g.GET("/users/:id", debugHandler) g.GET("/users/current", debugHandler) g.GET("/users/*path", debugHandler) }) log.Println("listening on http://localhost:9999") log.Println(http.ListenAndServe(":9999", router)) } func indexHandler(w http.ResponseWriter, req bunrouter.Request) error { return indexTemplate().Execute(w, nil) } func debugHandler(w http.ResponseWriter, req bunrouter.Request) error { return bunrouter.JSON(w, bunrouter.H{ "route": req.Route(), "params": req.Params().Map(), }) } var indexTmpl = `

Welcome

` func indexTemplate() *template.Template { return template.Must(template.New("index").Parse(indexTmpl)) } ``` -------------------------------- ### Version: Get BunRouter Release Version in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The Version function returns the current release version string of the BunRouter library. This is useful for dependency checking or logging purposes. ```go func Version() string { // ... implementation details ... } ``` -------------------------------- ### WithGroup: Go Function for Nested Group Configuration Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter WithGroup is a function that creates a GroupOption to configure a nested group. It takes a function `fn` which is executed with the new group, allowing for hierarchical routing setup. ```go func WithGroup(fn func(g *Group)) GroupOption ``` -------------------------------- ### Retrieve Route Parameters using Params in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The Params type holds route parameters and provides various methods for accessing and parsing them. You can retrieve parameters by name using ByName or Get, parse them as integers (Int, Int32, Int64, Uint32, Uint64), convert them to a map or slice, or check if parameters exist using IsZero. ```go func ParamsFromContext(ctx context.Context) Params ``` ```go func (ps Params) ByName(name string) string ``` ```go func (ps Params) Get(name string) (string, bool) ``` ```go func (ps Params) Int(name string) (int, error) ``` ```go func (ps Params) Int32(name string) (int32, error) ``` ```go func (ps Params) Int64(name string) (int64, error) ``` ```go func (ps Params) IsZero() bool ``` ```go func (ps Params) Map() map[string]string ``` ```go func (ps Params) Route() string ``` ```go func (ps Params) Slice() []Param ``` ```go func (ps Params) Uint32(name string) (uint32, error) ``` ```go func (ps Params) Uint64(name string) (uint64, error) ``` -------------------------------- ### Bunrouter VerboseGroup HTTP Methods Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The VerboseGroup type defines methods for registering handlers for various HTTP methods (DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT) along with a generic Handle method. ```go func (g VerboseGroup) DELETE(path string, handler VerboseHandlerFunc) func (g VerboseGroup) GET(path string, handler VerboseHandlerFunc) func (g VerboseGroup) HEAD(path string, handler VerboseHandlerFunc) func (g VerboseGroup) OPTIONS(path string, handler VerboseHandlerFunc) func (g VerboseGroup) PATCH(path string, handler VerboseHandlerFunc) func (g VerboseGroup) POST(path string, handler VerboseHandlerFunc) func (g VerboseGroup) PUT(path string, handler VerboseHandlerFunc) func (g VerboseGroup) Handle(method string, path string, handler VerboseHandlerFunc) ``` -------------------------------- ### Router Initialization and Core Functionality Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter This section details how to create and use the main Router, including its ServeHTTP methods for handling web requests. ```APIDOC ## Router ### Description Router is the main structure that implements HTTP request routing. It maintains a routing tree and handles incoming HTTP requests. ### Methods #### `New(opts ...Option) *Router` Creates and returns a new `Router` instance with the given options. Options can include middleware, custom handlers for 404 and 405 responses, and other router configurations. #### `ServeHTTP(w http.ResponseWriter, req *http.Request)` Implements the `http.Handler` interface. It processes the incoming HTTP request and routes it to the appropriate handler. #### `ServeHTTPError(w http.ResponseWriter, req *http.Request) error` Similar to `ServeHTTP` but also returns any error that occurred during request handling. Added in v1.0.9. #### `WithContext(ctx context.Context) Request` Returns a new `Request` with the provided context. Note: This is a method on the `Request` type, not directly on `Router`. ``` -------------------------------- ### Router Options: NotFoundHandler and MethodNotAllowedHandler Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Documentation for configuring custom handlers for 404 Not Found and 405 Method Not Allowed errors. ```APIDOC ## Router Options: NotFoundHandler and MethodNotAllowedHandler ### Description Configure custom handlers for specific error conditions: when no route matches the request (404 Not Found) and when a route matches but not for the requested HTTP method (405 Method Not Allowed). #### `func WithNotFoundHandler(handler HandlerFunc) Option` Sets a custom `HandlerFunc` to be executed when no registered route pattern matches the incoming request. The default handler is `http.NotFound`. #### `func WithMethodNotAllowedHandler(handler HandlerFunc) Option` Sets a custom `HandlerFunc` to be executed when a route pattern matches, but there is no handler defined for the specific HTTP method used in the request. The default handler returns `http.StatusMethodNotAllowed`. ``` -------------------------------- ### CompatGroup Methods Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter CompatGroup provides compatibility with http.HandlerFunc, allowing traditional Go handlers to be used within Bunrouter groups. ```APIDOC ## CompatGroup Type ### Description `CompatGroup` is similar to `Group` but works with `http.HandlerFunc` instead of `bunrouter.HandlerFunc`. ### Methods #### DELETE Registers a handler for DELETE requests. ```go func (g CompatGroup) DELETE(path string, handler http.HandlerFunc) ``` #### GET Registers a handler for GET requests. ```go func (g CompatGroup) GET(path string, handler http.HandlerFunc) ``` #### HEAD Registers a handler for HEAD requests. ```go func (g CompatGroup) HEAD(path string, handler http.HandlerFunc) ``` #### Handle Registers a handler for a specific HTTP method and path. ```go func (g CompatGroup) Handle(method string, path string, handler http.HandlerFunc) ``` #### NewGroup Creates a new nested `CompatGroup`. ```go func (g CompatGroup) NewGroup(path string, opts ...GroupOption) *CompatGroup ``` #### OPTIONS Registers a handler for OPTIONS requests. ```go func (g CompatGroup) OPTIONS(path string, handler http.HandlerFunc) ``` #### PATCH Registers a handler for PATCH requests. ```go func (g CompatGroup) PATCH(path string, handler http.HandlerFunc) ``` #### POST Registers a handler for POST requests. ```go func (g CompatGroup) POST(path string, handler http.HandlerFunc) ``` #### PUT Registers a handler for PUT requests. ```go func (g CompatGroup) PUT(path string, handler http.HandlerFunc) ``` #### WithGroup Applies a function to configure a sub-group. ```go func (g CompatGroup) WithGroup(path string, fn func(g *CompatGroup)) ``` #### WithMiddleware Applies middleware to this `CompatGroup`. ```go func (g CompatGroup) WithMiddleware(middleware MiddlewareFunc) *CompatGroup ``` ``` -------------------------------- ### Middleware and Group Options Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Explains how to add middleware to request handling pipelines and configure group options. ```APIDOC ## Middleware and Group Options ### Description These functions allow you to enhance request processing by adding middleware or configuring options for route groups. #### `func WithMiddleware(fns ...MiddlewareFunc) GroupOption` Adds one or more `MiddlewareFunc` to the middleware stack for a route group. Middleware can intercept and process requests before they reach the final handler. #### `func WithHandler(fn HandlerFunc) GroupOption` Similar to `WithMiddleware`, but the provided `HandlerFunc` cannot modify the request. This is useful for handlers that only perform actions without altering the request context. ### MiddlewareFunc Type ```go type MiddlewareFunc func(next HandlerFunc) HandlerFunc ``` `MiddlewareFunc` is a function that wraps another `HandlerFunc`. It allows you to execute logic before and/or after the `next` handler is called, enabling common middleware patterns like logging, authentication, or request modification. ``` -------------------------------- ### Bunrouter Router ServeHTTP Implementation Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter ServeHTTP implements the http.Handler interface for the Router. It processes incoming HTTP requests and directs them to the appropriate registered handler based on the request method and path. ```go func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { // Implementation details not provided in snippet } ``` -------------------------------- ### Use: Go Function for Applying Middleware to Groups Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The Use function, added in v1.0.11, is an alias for WithMiddleware. It provides a convenient way to apply one or more middleware functions to a group. ```go func Use(fns ...MiddlewareFunc) GroupOption ``` -------------------------------- ### Request and Parameters Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Details on the extended `Request` type and how to access route parameters. ```APIDOC ## Request and Parameters ### Description This section covers the `Request` type, which extends the standard `http.Request`, and the `Params` type used for accessing route parameters. #### `type Request struct { *http.Request }` The `Request` type embeds `*http.Request` and adds functionality for accessing route-specific information. ##### `func NewRequest(req *http.Request) Request` Creates a new `Request` instance from a standard `*http.Request`. ##### `func (req Request) Param(key string) string` Retrieves the value of a named path parameter by its key. Returns an empty string if the parameter is not found. ##### `func (req Request) Params() Params` Returns the `Params` object associated with the request, containing all route parameters. ##### `func (req Request) Route() string` Returns the matched route pattern for the current request. #### `type Params` `Params` holds route parameters and related information. ##### `func ParamsFromContext(ctx context.Context) Params` Retrieves route parameters from the request context. Returns an empty `Params` if none are found. ##### `func (ps Params) ByName(name string) string` Returns the value of a named parameter. If not found, returns an empty string. ##### `func (ps Params) Get(name string) (string, bool)` Returns the value of a named parameter and a boolean indicating whether it was found. ##### `func (ps Params) Int(name string) (int, error)` Parses the named parameter as an integer. ##### `func (ps Params) Int32(name string) (int32, error)` Parses the named parameter as a signed 32-bit integer. ##### `func (ps Params) Int64(name string) (int64, error)` Parses the named parameter as a signed 64-bit integer. ##### `func (ps Params) Uint32(name string) (uint32, error)` Parses the named parameter as an unsigned 32-bit integer. ##### `func (ps Params) Uint64(name string) (uint64, error)` Parses the named parameter as an unsigned 64-bit integer. ##### `func (ps Params) Map() map[string]string` Returns all route parameters as a `map[string]string`. ##### `func (ps Params) Slice() []Param` Returns route parameters as a slice of `Param` structs. ##### `func (ps Params) Route() string` Returns the route pattern that matched the request. ##### `func (ps Params) IsZero() bool` Checks if the `Params` object is empty (i.e., no route node associated). ``` -------------------------------- ### Utilities and Options Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Utility functions and configuration options for the router. ```APIDOC ## Utilities and Options ### Description This section details utility functions and configuration options for customizing the Bunrouter behavior. ### Utility Functions - **CleanPath(p string) string**: Cleans a URL path. - **JSON(w http.ResponseWriter, value interface{}) error**: Writes a JSON response. - **Version() string**: Returns the router's version. ### Options - **New(opts ...Option) *Router**: Creates a new router instance with optional configurations. - **WithNotFoundHandler(handler HandlerFunc) Option**: Sets a custom handler for 404 Not Found errors. - **WithMethodNotAllowedHandler(handler HandlerFunc) Option**: Sets a custom handler for 405 Method Not Allowed errors. ``` -------------------------------- ### Bunrouter Router Compatibility and Verbose Wrappers Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The Router provides methods Compat and Verbose to return wrapper instances, CompatRouter and VerboseRouter respectively. These wrappers offer alternative interfaces for interacting with the router. ```go func (r *Router) Compat() *CompatRouter func (r *Router) Verbose() *VerboseRouter ``` -------------------------------- ### Request and Parameter Handling Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Access request details and route parameters. ```APIDOC ## Request and Parameter Handling ### Description This section covers how to access request details and extract parameters from the URL path. ### Request Methods - **NewRequest(req *http.Request) Request**: Creates a Bunrouter `Request` object from an `http.Request`. - **Param(key string) string**: Retrieves a path parameter by its key. - **Params() Params**: Returns all path parameters. - **Route() string**: Returns the matched route path. ### Params Methods - **ParamsFromContext(ctx context.Context) Params**: Retrieves `Params` from a context. - **ByName(name string) string**: Gets a parameter value by name. - **Get(name string) (string, bool)**: Safely gets a parameter value. - **Int(name string) (int, error)**: Gets a parameter value as an integer. - **Map() map[string]string**: Returns all parameters as a map. ``` -------------------------------- ### Version Information Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Retrieves the current release version of the Bunrouter library. ```APIDOC ## Version Function ### Description Returns the current release version of the Bunrouter library. ### Signature ```go func Version() string ``` ### Returns * (string) - The current version string. ``` -------------------------------- ### Router Methods Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter This section covers the primary methods for defining routes within the Bunrouter. ```APIDOC ## Router Methods ### Description This section details the methods available on the `Router` and `CompatRouter` types for handling HTTP requests. ### Methods - **GET(path string, handler HandlerFunc)**: Registers a handler for GET requests to the specified path. - **POST(path string, handler HandlerFunc)**: Registers a handler for POST requests to the specified path. - **PUT(path string, handler HandlerFunc)**: Registers a handler for PUT requests to the specified path. - **DELETE(path string, handler HandlerFunc)**: Registers a handler for DELETE requests to the specified path. - **PATCH(path string, handler HandlerFunc)**: Registers a handler for PATCH requests to the specified path. - **HEAD(path string, handler HandlerFunc)**: Registers a handler for HEAD requests to the specified path. - **OPTIONS(path string, handler HandlerFunc)**: Registers a handler for OPTIONS requests to the specified path. - **Handle(meth string, path string, handler HandlerFunc)**: Registers a handler for any HTTP method to the specified path. ### CompatRouter Methods The `CompatRouter` provides similar methods but adheres to a compatibility layer. - **Compat().GET(path string, handler http.HandlerFunc)** - **Compat().POST(path string, handler http.HandlerFunc)** - **Compat().PUT(path string, handler http.HandlerFunc)** - **Compat().DELETE(path string, handler http.HandlerFunc)** - **Compat().PATCH(path string, handler http.HandlerFunc)** - **Compat().HEAD(path string, handler http.HandlerFunc)** - **Compat().OPTIONS(path string, handler http.HandlerFunc)** - **Compat().Handle(method string, path string, handler http.HandlerFunc)** ``` -------------------------------- ### Convert net/http HandlerFunc to Bunrouter HandlerFunc in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Similar to HTTPHandler, HTTPHandlerFunc provides a way to convert a standard Go http.HandlerFunc to bunrouter's HandlerFunc. This utility is essential for leveraging existing http.HandlerFunc implementations within a bunrouter context, simplifying integration. ```go func HTTPHandlerFunc(handler http.HandlerFunc) HandlerFunc ``` -------------------------------- ### Add Middleware to Bunrouter Group in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter WithMiddleware is a GroupOption that allows you to attach one or more MiddlewareFunc to a specific route group. This is crucial for applying common middleware logic to a set of related routes, such as applying authentication to all routes within an /api group. ```go func WithMiddleware(fns ...MiddlewareFunc) GroupOption ``` -------------------------------- ### GroupOption: Go Interface for Group Configuration Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter GroupOption is an interface that extends the Option interface, used for configuring groups within BunRouter. It is typically implemented by options that modify group behavior. ```go type GroupOption interface { Option // contains filtered or unexported methods } ``` -------------------------------- ### Bunrouter Request WithContext Method Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The WithContext method on the Request type creates a new Request with a provided context. This is useful for managing request-scoped values and cancellation signals. ```go func (req Request) WithContext(ctx context.Context) Request { // Implementation details not provided in snippet } ``` -------------------------------- ### Implement Bunrouter MiddlewareFunc in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter MiddlewareFunc defines the structure for middleware in bunrouter. It takes a HandlerFunc and returns a new HandlerFunc, allowing you to wrap request handling logic for tasks like authentication, logging, or request modification. This enables a flexible middleware pipeline. ```go type MiddlewareFunc func(next HandlerFunc) HandlerFunc ``` -------------------------------- ### CompatRouter: Go Compatibility Layer for BunRouter Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter CompatRouter provides a compatibility layer for the BunRouter, embedding both the main Router and a CompatGroup. This allows for easier integration with existing http.HandlerFunc based middleware or handlers. ```go type CompatRouter struct { *Router *CompatGroup } ``` -------------------------------- ### Group Methods Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Group allows organizing routes and applying middlewares hierarchically. It supports standard HTTP methods and custom handlers. ```APIDOC ## Group Type ### Description `Group` represents a collection of routes and middlewares. It allows for nested routing configurations. ### Methods #### Compat Returns a `CompatGroup` representation of this group. ```go func (g *Group) Compat() *CompatGroup ``` #### DELETE Syntactic sugar for registering a DELETE handler. ```go func (g *Group) DELETE(path string, handler HandlerFunc) ``` #### GET Syntactic sugar for registering a GET handler. ```go func (g *Group) GET(path string, handler HandlerFunc) ``` #### HEAD Syntactic sugar for registering a HEAD handler. ```go func (g *Group) HEAD(path string, handler HandlerFunc) ``` #### Handle Registers a handler for a specific HTTP method and path. ```go func (g *Group) Handle(meth string, path string, handler HandlerFunc) ``` #### NewGroup Creates and returns a new sub-group attached to this group. ```go func (g *Group) NewGroup(path string, opts ...GroupOption) *Group ``` #### OPTIONS Syntactic sugar for registering an OPTIONS handler. ```go func (g *Group) OPTIONS(path string, handler HandlerFunc) ``` #### PATCH Syntactic sugar for registering a PATCH handler. ```go func (g *Group) PATCH(path string, handler HandlerFunc) ``` #### POST Syntactic sugar for registering a POST handler. ```go func (g *Group) POST(path string, handler HandlerFunc) ``` #### PUT Syntactic sugar for registering a PUT handler. ```go func (g *Group) PUT(path string, handler HandlerFunc) ``` #### Use Adds one or more middlewares to the group. ```go func (g *Group) Use(middlewares ...MiddlewareFunc) *Group ``` #### Verbose Returns a `VerboseGroup` which might offer more detailed routing information. ```go func (g *Group) Verbose() *VerboseGroup ``` #### WithGroup Creates a nested group and applies a configuration function to it. ```gogo func (g *Group) WithGroup(path string, fn func(g *Group)) ``` #### WithMiddleware Applies a middleware to this group and returns the modified group. ```go func (g *Group) WithMiddleware(middleware MiddlewareFunc) *Group ``` ``` -------------------------------- ### Configure Bunrouter NotFoundHandler in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter WithNotFoundHandler allows you to customize the handler that is invoked when no route pattern matches the incoming request. This is essential for providing user-friendly 404 pages or custom error responses when a requested resource is not found. ```go func WithNotFoundHandler(handler HandlerFunc) Option ``` -------------------------------- ### Type Aliases and Interfaces Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Defines common type aliases and interfaces used within the Bunrouter library. ```APIDOC ## Type Aliases and Interfaces ### Description Provides definitions for fundamental types and interfaces used in Bunrouter, such as shorthand map types, error handling, and options. #### `type H map[string]interface{}` `H` is a type alias for `map[string]interface{}`, commonly used for request or response data structures. #### `type HTTPError interface { error; StatusCode() int }` `HTTPError` is an interface that represents an error with an associated HTTP status code. Implementations of this interface allow for consistent error handling with status codes. #### `type Option interface` `Option` is an interface used for configuring router behavior, typically passed during router initialization. It abstracts various configuration settings. ``` -------------------------------- ### Bunrouter VerboseGroup Grouping and Middleware Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter VerboseGroup allows for creating nested route groups using NewGroup and applying middleware with WithMiddleware. It also supports configuring sub-groups with functions using WithGroup. ```go func (g VerboseGroup) NewGroup(path string, opts ...GroupOption) *VerboseGroup func (g VerboseGroup) WithGroup(path string, fn func(g *VerboseGroup)) func (g VerboseGroup) WithMiddleware(middleware MiddlewareFunc) *VerboseGroup ``` -------------------------------- ### Verbose Routing Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Documentation for the VerboseRouter and VerboseGroup types, which provide a more detailed interface for routing. ```APIDOC ## Verbose Routing ### Description VerboseRouter and VerboseGroup offer a detailed interface for router configuration and request handling, working with `VerboseHandlerFunc`. ### Types #### `VerboseHandlerFunc` `type VerboseHandlerFunc func(w http.ResponseWriter, req *http.Request, ps Params)` A handler function type for verbose routing. #### `VerboseRouter` `type VerboseRouter struct { *Router; *VerboseGroup }` Provides a verbose interface to the router. #### `VerboseGroup` `type VerboseGroup struct { ... }` Similar to `Group`, but works with `VerboseHandlerFunc`. ### `VerboseGroup` Methods - **`DELETE(path string, handler VerboseHandlerFunc)`**: Registers a DELETE handler. - **`GET(path string, handler VerboseHandlerFunc)`**: Registers a GET handler. - **`HEAD(path string, handler VerboseHandlerFunc)`**: Registers a HEAD handler. - **`Handle(method string, path string, handler VerboseHandlerFunc)`**: Registers a handler for a specific HTTP method and path. - **`NewGroup(path string, opts ...GroupOption) *VerboseGroup`**: Creates a new nested `VerboseGroup`. - **`OPTIONS(path string, handler VerboseHandlerFunc)`**: Registers an OPTIONS handler. - **`PATCH(path string, handler VerboseHandlerFunc)`**: Registers a PATCH handler. - **`POST(path string, handler VerboseHandlerFunc)`**: Registers a POST handler. - **`PUT(path string, handler VerboseHandlerFunc)`**: Registers a PUT handler. - **`WithGroup(path string, fn func(g *VerboseGroup))`**: Applies configurations to a nested `VerboseGroup`. - **`WithMiddleware(middleware MiddlewareFunc) *VerboseGroup`**: Adds middleware to the `VerboseGroup`. ``` -------------------------------- ### Group Options Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter GroupOption is an interface for configuring groups, including applying middlewares or nested group configurations. ```APIDOC ## GroupOption Type ### Description `GroupOption` is an interface that defines options for configuring route groups. It embeds the `Option` interface. ### Functions #### Use An alias for `WithMiddleware`, creating a `GroupOption` that applies middlewares. ```go func Use(fns ...MiddlewareFunc) GroupOption ``` #### WithGroup Creates a `GroupOption` that executes a function `fn` with a given `Group`. ```go func WithGroup(fn func(g *Group)) GroupOption ``` ``` -------------------------------- ### Group Management Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Manage nested routing groups and apply middleware to them. ```APIDOC ## Group Management ### Description Bunrouter allows for the creation of nested route groups, enabling better organization and the application of middleware to a set of routes. ### Group Methods - **NewGroup(path string, opts ...GroupOption) *Group**: Creates a new nested group with the given path prefix and options. - **WithGroup(path string, fn func(g *Group))**: Creates a new group and applies configuration within the provided function. - **Use(middlewares ...MiddlewareFunc) *Group**: Applies middleware to the current group and its nested groups. ### CompatGroup Methods The `CompatGroup` offers similar functionality for compatibility. - **CompatGroup.NewGroup(path string, opts ...GroupOption) *CompatGroup** - **CompatGroup.WithGroup(path string, fn func(g *CompatGroup))** - **CompatGroup.WithMiddleware(middleware MiddlewareFunc) *CompatGroup** ``` -------------------------------- ### CompatGroup: Go Type for HTTP HandlerFunc Group Routing Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter CompatGroup is a type that mirrors the functionality of Group but is designed to work with standard http.HandlerFunc instead of BunRouter's HandlerFunc. It allows for routing HTTP requests using the familiar http.HandlerFunc. ```go type CompatGroup struct { // contains filtered or unexported fields } ``` ```go func (g CompatGroup) DELETE(path string, handler http.HandlerFunc) ``` ```go func (g CompatGroup) GET(path string, handler http.HandlerFunc) ``` ```go func (g CompatGroup) HEAD(path string, handler http.HandlerFunc) ``` ```go func (g CompatGroup) Handle(method string, path string, handler http.HandlerFunc) ``` ```go func (g CompatGroup) NewGroup(path string, opts ...GroupOption) *CompatGroup ``` ```go func (g CompatGroup) OPTIONS(path string, handler http.HandlerFunc) ``` ```go func (g CompatGroup) PATCH(path string, handler http.HandlerFunc) ``` ```go func (g CompatGroup) POST(path string, handler http.HandlerFunc) ``` ```go func (g CompatGroup) PUT(path string, handler http.HandlerFunc) ``` ```go func (g CompatGroup) WithGroup(path string, fn func(g *CompatGroup)) ``` ```go func (g CompatGroup) WithMiddleware(middleware MiddlewareFunc) *CompatGroup ``` -------------------------------- ### Convert net/http Handler to Bunrouter HandlerFunc in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The HTTPHandler function allows you to seamlessly integrate existing net/http Handlers into your bunrouter application. This is useful for migrating existing code or using third-party libraries that expose http.Handler interfaces. It ensures compatibility between standard Go HTTP handlers and bunrouter's HandlerFunc. ```go func HTTPHandler(handler http.Handler) HandlerFunc ``` -------------------------------- ### Create Bunrouter Request from http.Request in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter NewRequest is a constructor function that creates a bunrouter.Request from a standard http.Request. The bunrouter.Request extends http.Request by adding route parameters and other routing-specific information, making it the primary object for accessing request details within bunrouter handlers. ```go func NewRequest(req *http.Request) Request ``` -------------------------------- ### Access Route Parameters from Bunrouter Request in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The Request type in bunrouter extends http.Request and provides methods to access route parameters. Param retrieves a single parameter by key, while Params returns all route parameters associated with the request. Route returns the matched route pattern. ```go func (req Request) Param(key string) string ``` ```go func (req Request) Params() Params ``` ```go func (req Request) Route() string ``` -------------------------------- ### Bunrouter Router Structure and Initialization Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The Router struct is the main component for HTTP request routing in Bunrouter. It embeds a route group and maintains a routing tree. The New function initializes a Router with optional configurations. ```go type Router struct { Group // embedded route group // contains filtered or unexported fields } func New(opts ...Option) *Router { // Implementation details not provided in snippet } ``` -------------------------------- ### Define Bunrouter HandlerFunc with Handler Option in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter WithHandler is a GroupOption similar to WithMiddleware, but it enforces that the provided handler function cannot modify the request object. This is useful for defining read-only handlers within a group, ensuring that request state is preserved across middleware or other handlers. ```go func WithHandler(fn HandlerFunc) GroupOption ``` -------------------------------- ### CompatRouter Type Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter CompatRouter offers a compatibility layer for the Bunrouter, integrating both Router and CompatGroup functionalities. ```APIDOC ## CompatRouter Type ### Description `CompatRouter` provides a compatibility layer for the router, combining `Router` and `CompatGroup` functionalities. ### Fields * **Router** (*Router) - Embedded Router instance. * **CompatGroup** (*CompatGroup) - Embedded CompatGroup instance. ``` -------------------------------- ### Configure Bunrouter MethodNotAllowedHandler in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter WithMethodNotAllowedHandler lets you specify a handler to be executed when a route matches but the requested HTTP method is not supported for that route. This is useful for returning specific error messages or actions when a client uses an incorrect HTTP verb (e.g., POST on a GET-only endpoint). ```go func WithMethodNotAllowedHandler(handler HandlerFunc) Option ``` -------------------------------- ### Path Cleaning Utility Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The CleanPath function normalizes URL paths by removing redundant slashes, '.' and '..' elements, and ensures a canonical representation. ```APIDOC ## CleanPath Function ### Description Cleans a URL path by removing redundant slashes and '..', returning a canonical path. ### Signature ```go func CleanPath(p string) string ``` ### Parameters * **p** (string) - The path to clean. ### Returns * (string) - The cleaned, canonical path. ``` -------------------------------- ### Group: Go Type for Route Grouping and Middleware Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Group is a type used for organizing routes and applying middleware in BunRouter. It allows for nested groups and provides syntactic sugar for common HTTP methods. ```go type Group struct { // contains filtered or unexported fields } ``` ```go func (g *Group) Compat() *CompatGroup ``` ```go func (g *Group) DELETE(path string, handler HandlerFunc) ``` ```go func (g *Group) GET(path string, handler HandlerFunc) ``` ```go func (g *Group) HEAD(path string, handler HandlerFunc) ``` ```go func (g *Group) Handle(meth string, path string, handler HandlerFunc) ``` ```go func (g *Group) NewGroup(path string, opts ...GroupOption) *Group ``` ```go func (g *Group) OPTIONS(path string, handler HandlerFunc) ``` ```go func (g *Group) PATCH(path string, handler HandlerFunc) ``` ```go func (g *Group) POST(path string, handler HandlerFunc) ``` ```go func (g *Group) PUT(path string, handler HandlerFunc) ``` ```go func (g *Group) Use(middlewares ...MiddlewareFunc) *Group ``` ```go func (g *Group) Verbose() *VerboseGroup ``` ```go func (g *Group) WithGroup(path string, fn func(g *Group)) ``` ```go func (g *Group) WithMiddleware(middleware MiddlewareFunc) *Group ``` -------------------------------- ### Bunrouter VerboseRouter and VerboseGroup Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter VerboseRouter provides an enhanced interface for routing, working with VerboseGroup and VerboseHandlerFunc. VerboseGroup mirrors the functionality of Group but with verbose handlers. ```go type VerboseHandlerFunc func(w http.ResponseWriter, req *http.Request, ps Params) type VerboseGroup struct { // contains filtered or unexported fields } type VerboseRouter struct { *Router *VerboseGroup } ``` -------------------------------- ### JSON Response Helper Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The JSON function marshals an interface{} value to JSON and writes it to the http.ResponseWriter, setting the Content-Type to 'application/json'. ```APIDOC ## JSON Function ### Description Marshals the given value to JSON and writes it to the http.ResponseWriter. Sets the `Content-Type` header to `application/json`. ### Signature ```go func JSON(w http.ResponseWriter, value interface{}) error ``` ### Parameters * **w** (http.ResponseWriter) - The response writer to write the JSON to. * **value** (interface{}) - The data to marshal and send as JSON. ### Returns * (error) - An error if the marshaling or writing fails. ``` -------------------------------- ### HandlerFunc and Related Functions Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter Defines the HandlerFunc type for handling HTTP requests and functions for converting standard http.Handler types to HandlerFunc. ```APIDOC ## HandlerFunc and Related Functions ### Description Defines the HandlerFunc type for handling HTTP requests and provides utility functions to convert standard `http.Handler` and `http.HandlerFunc` into `bunrouter.HandlerFunc`. ### HandlerFunc Type ```go type HandlerFunc func(w http.ResponseWriter, req Request) error ``` `HandlerFunc` is the primary function signature for handling HTTP requests within Bunrouter. It receives an `http.ResponseWriter` and a custom `Request` object and returns an error that the router will manage. ### Conversion Functions #### `func HTTPHandler(handler http.Handler) HandlerFunc` Converts a standard `http.Handler` to a `bunrouter.HandlerFunc`. #### `func HTTPHandlerFunc(handler http.HandlerFunc) HandlerFunc` Converts a standard `http.HandlerFunc` to a `bunrouter.HandlerFunc`. ``` -------------------------------- ### JSON: Function to Write JSON Responses in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The JSON function marshals an interface{} value into JSON format and writes it to an http.ResponseWriter. It automatically sets the Content-Type header to 'application/json'. This function can be customized by copying it into your project. ```go func JSON(w http.ResponseWriter, value interface{}) error { // ... implementation details ... } ``` -------------------------------- ### CleanPath: Canonical URL Path Function in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The CleanPath function normalizes a URL path by removing redundant elements like '.' and '..', and resolving multiple slashes. It ensures a canonical representation of the path, returning '/' if the result is an empty string. ```go func CleanPath(p string) string { // ... implementation details ... } ``` -------------------------------- ### Define Bunrouter HandlerFunc in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter HandlerFunc is the core function signature for handling HTTP requests in bunrouter. It accepts an http.ResponseWriter and a bunrouter.Request, returning an error that the router will manage. This is fundamental for defining how your application responds to incoming requests. ```go type HandlerFunc func(w http.ResponseWriter, req Request) error ``` -------------------------------- ### Bunrouter Router ServeHTTPError Method Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter ServeHTTPError is an extension of ServeHTTP that also returns any error encountered during request processing. This aids in detailed error handling and logging. ```go func (r *Router) ServeHTTPError(w http.ResponseWriter, req *http.Request) error { // Implementation details not provided in snippet } ``` -------------------------------- ### Define Bunrouter HTTPError Interface in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter The HTTPError interface extends the standard Go error interface by including a StatusCode() method. This allows handlers to return errors that include specific HTTP status codes, enabling the router to send appropriate responses for errors like 'Not Found' or 'Internal Server Error'. ```go type HTTPError interface { error StatusCode() int } ``` -------------------------------- ### Define Bunrouter H type alias in Go Source: https://bunrouter.uptrace.dev/guide/golang-router.html/github.com/uptrace/bunrouter H is a type alias for map[string]interface{}, providing a shorthand for creating maps that are commonly used for request payloads, response data, or configuration options within bunrouter applications. It simplifies the declaration of flexible key-value data structures. ```go type H map[string]interface{} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.