Documentation
¶
Index ¶
- func Lift[O any](responder *Responder, action func(*http.Request) (O, error)) http.Handler
- func LoggerFromContext(ctx context.Context) *slog.Logger
- func NewContextWithLogger(ctx context.Context, l *slog.Logger) context.Context
- func PrintRoutes(w io.Writer, b *Builder)
- func SSE[T any](responder *Responder, w http.ResponseWriter, req *http.Request, ch <-chan T)
- func WithLogger(l *slog.Logger) func(*BuilderConfig)
- func WithOnConflict(onConflict func(b *Builder, routeKey string) error) func(*BuilderConfig)
- type APIError
- type Builder
- func (b *Builder) Build() (http.Handler, error)
- func (b *Builder) Delete(pattern string, handler http.Handler)
- func (b *Builder) Get(pattern string, handler http.Handler)
- func (b *Builder) Group(fn func(b *Builder))
- func (b *Builder) NotFound(handler http.Handler)
- func (b *Builder) Patch(pattern string, handler http.Handler)
- func (b *Builder) Post(pattern string, handler http.Handler)
- func (b *Builder) Put(pattern string, handler http.Handler)
- func (b *Builder) Route(pattern string, fn func(b *Builder))
- func (b *Builder) Use(middleware Middleware)
- func (b *Builder) Walk(fn func(method string, pattern string))
- type BuilderConfig
- type Event
- type Middleware
- type RedirectError
- type Responder
- func (r *Responder) Error(w http.ResponseWriter, req *http.Request, statusCode int, err error)
- func (r *Responder) HTML(w http.ResponseWriter, req *http.Request, code int, html []byte)
- func (r *Responder) JSON(w http.ResponseWriter, req *http.Request, statusCode int, data any)
- func (r *Responder) Redirect(w http.ResponseWriter, req *http.Request, url string, code int)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Lift ¶
Lift converts a function that returns a value and an error into an http.Handler.
The action function has the signature: func(*http.Request) (O, error)
- If the error is nil, the returned value of type O is encoded as a JSON response with a 200 OK status.
- If the error is not nil:
- To perform a redirect, return a `*RedirectError`. Lift will handle the redirect and no further response will be written.
- If the error has a StatusCode() int method (like `APIError`), its status code is used for the response.
- Otherwise, a 500 Internal Server Error is returned.
- The error message is returned as a JSON object: {"error": "message"}.
- For 5xx errors, the original error is logged, but a generic "Internal Server Error" message is returned to the client to avoid exposing internal details.
- If both the returned value and the error are nil, it follows specific rules:
- For `nil` maps, it returns `200 OK` with an empty JSON object `{}`.
- For `nil` slices, it returns `200 OK` with an empty JSON array `[]`.
- For other nillable types (e.g., pointers), it returns `204 No Content`.
func LoggerFromContext ¶ added in v0.0.3
LoggerFromContext retrieves the Logger from the context. If no logger is found, it falls back to slog.Default() and logs a warning on the first call.
func NewContextWithLogger ¶ added in v0.0.3
NewContextWithLogger returns a new context with the provided Logger.
func PrintRoutes ¶
PrintRoutes prints a formatted table of all registered routes to the provided writer.
func SSE ¶
SSE streams data from a channel to the client using the Server-Sent Events protocol. It sets the appropriate headers and handles the event stream formatting. The channel element type T can be any marshalable type. If T is of type Event[U] or *Event[U], it will be treated as a named event.
func WithLogger ¶
func WithLogger(l *slog.Logger) func(*BuilderConfig)
WithLogger sets the logger for the Builder.
func WithOnConflict ¶ added in v0.0.4
func WithOnConflict(onConflict func(b *Builder, routeKey string) error) func(*BuilderConfig)
WithOnConflict sets the OnConflict handler for the Builder.
Types ¶
type APIError ¶
type APIError struct {
// contains filtered or unexported fields
}
APIError is an error type that includes an HTTP status code.
func NewAPIError ¶
NewAPIError creates a new APIError, capturing the caller's position. The default depth is 2, which points to the caller of NewAPIError.
func NewAPIErrorWithDepth ¶ added in v0.0.4
NewAPIErrorWithDepth creates a new APIError with a specific call stack depth.
func NewAPIErrorf ¶
NewAPIErrorf creates a new APIError with a formatted message. The default depth is 2, which points to the caller of NewAPIErrorf.
func (*APIError) StatusCode ¶
StatusCode returns the HTTP status code.
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder is the configuration object for the router. It is used to define routes and middlewares. It does not implement http.Handler.
func NewBuilder ¶
func NewBuilder(options ...func(*BuilderConfig)) *Builder
NewBuilder creates a new Builder instance with the given options.
func (*Builder) Build ¶
Build creates a new http.Handler from the configured routes. The returned handler is immutable.
func (*Builder) NotFound ¶
NotFound sets a custom handler for 404 Not Found responses. If not set, a default JSON response is used.
func (*Builder) Use ¶
func (b *Builder) Use(middleware Middleware)
Use adds a middleware to the current builder's node.
type BuilderConfig ¶ added in v0.0.4
type BuilderConfig struct {
Logger *slog.Logger
// OnConflict defines a function to be called when a route conflict is detected.
// It receives the builder and the conflicting route key. It can return an error
// to halt the build process. If it returns nil, the conflict is ignored and the
// duplicate route is not registered.
OnConflict func(b *Builder, routeKey string) error
}
BuilderConfig holds the configuration for a Builder.
type Event ¶
type Event[T any] struct { // Name is the event name. If empty, it will be omitted. Name string // Data is the payload for the event. Data T }
Event represents a single Server-Sent Event.
type Middleware ¶
Middleware is a function that wraps an http.Handler.
type RedirectError ¶ added in v0.0.3
RedirectError is a special error type used to signal an HTTP redirect. When this error is returned from a handler wrapped by Lift, the Lift function will perform the redirect and stop further processing.
func (*RedirectError) Error ¶ added in v0.0.3
func (e *RedirectError) Error() string
Error implements the error interface.
type Responder ¶
type Responder struct{}
Responder handles writing JSON responses.
func (*Responder) Error ¶ added in v0.0.3
Error sends a JSON error response. It logs errors only under specific conditions: - If the status code is >= 500. - If the logger's level is Debug or lower. For 5xx errors, it sends a generic message to the client.
func (*Responder) HTML ¶ added in v0.0.3
HTML sends an HTML response to the client. This method is intended for use in standard http.Handlers, not with Lift, which is designed for JSON APIs.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package binding provides a type-safe, reflect-free, and expression-oriented way to bind data from HTTP requests to Go structs.
|
Package binding provides a type-safe, reflect-free, and expression-oriented way to bind data from HTTP requests to Go structs. |
|
examples
|
|
|
middleware-demonstration
command
|
|
|
simple-rest-api
command
|
|
|
spa-with-embed
command
|
|