Documentation
¶
Overview ¶
Package api implements the HTTP server module. Other modules register multipart/form data routes, middlewares, and health checks through it.
Example (Router) ¶
This example writes a module adding a route to the API. The interface guards make the compiler check that the module is what the application looks for.
package main
import (
"fmt"
"net/http"
"github.com/labstack/echo/v5"
"github.com/gotenberg/gotenberg/v9/pkg/gotenberg"
"github.com/gotenberg/gotenberg/v9/pkg/modules/api"
)
// Stamp is a module adding the multipart/form-data route /forms/stamp. A
// custom build registers it in an init function, then imports its package,
// next to github.com/gotenberg/gotenberg/v9/pkg/standard, in a main calling
// github.com/gotenberg/gotenberg/v9/cmd.Run.
type Stamp struct{}
// Descriptor returns the module's descriptor.
func (Stamp) Descriptor() gotenberg.ModuleDescriptor {
return gotenberg.ModuleDescriptor{
ID: "stamp",
New: func() gotenberg.Module { return new(Stamp) },
}
}
// Routes returns the module's routes.
func (Stamp) Routes() ([]api.Route, error) {
return []api.Route{
{
Method: http.MethodPost,
Path: "/forms/stamp",
IsMultipart: true,
Handler: func(c *echo.Context) error {
// The API builds the context of a multipart route: the
// uploaded files, the form fields, and the working directory.
ctx := c.Get("context").(*api.Context)
var inputPaths []string
var text string
err := ctx.FormData().
MandatoryPaths([]string{".pdf"}, &inputPaths).
String("text", &text).
Validate()
if err != nil {
return fmt.Errorf("validate form data: %w", err)
}
// Write the results under ctx.GeneratePath(".pdf") and register
// them: the API sends them back, zipped if many, or to the
// webhook.
return ctx.AddOutputPaths(inputPaths...)
},
},
}, nil
}
// This example writes a module adding a route to the API. The interface
// guards make the compiler check that the module is what the application
// looks for.
func main() {
var (
_ gotenberg.Module = (*Stamp)(nil)
_ api.Router = (*Stamp)(nil)
)
routes, _ := Stamp{}.Routes()
for _, route := range routes {
fmt.Println(route.Method, route.Path)
}
}
Output: POST /forms/stamp
Index ¶
- Constants
- Variables
- func ContentDisposition(filename string) string
- func Max(maximum int) func(int) error
- func Min(minimum int) func(int) error
- func OneOf(values ...int) func(int) error
- func OrList(values []string) string
- func PaperSizeInches(name string) (width, height float64, ok bool)
- func ParseError(err error) (int, string)
- func ParseInches(value string) (float64, error)
- func RouteAnswersDirectly(c *echo.Context) bool
- func SanitizeFilename(name string) string
- func WrapError(err error, sentinel SentinelHttpError) error
- type Api
- type AsynchronousCounter
- type Context
- func (ctx *Context) AddOutputPaths(paths ...string) error
- func (ctx *Context) BuildOutputFile() (string, error)
- func (ctx *Context) CreateSubDirectory(dirName string) (string, error)
- func (ctx *Context) DirPath() string
- func (ctx *Context) FileCount() int
- func (ctx *Context) FormData() *FormData
- func (ctx *Context) GeneratePath(extension string) string
- func (ctx *Context) GeneratePathFromFilename(filename string) string
- func (ctx *Context) Log() *slog.Logger
- func (ctx *Context) OriginalFilename(diskPath string) string
- func (ctx *Context) OutputFilename(outputPath string) string
- func (ctx *Context) OutputHeaders() map[string]string
- func (ctx *Context) RegisterDiskPath(diskPath, originalFilename string)
- func (ctx *Context) Rename(oldpath, newpath string) error
- func (ctx *Context) Request() *http.Request
- func (ctx *Context) SetOutputHeader(key, value string)
- func (ctx *Context) Timeout() time.Duration
- type ContextMock
- func (ctx *ContextMock) DirPath() string
- func (ctx *ContextMock) OutputPaths() []string
- func (ctx *ContextMock) SetCancelled(cancelled bool)
- func (ctx *ContextMock) SetDirPath(path string)
- func (ctx *ContextMock) SetEchoContext(c *echo.Context)
- func (ctx *ContextMock) SetFileFields(fields ...string)
- func (ctx *ContextMock) SetFiles(files map[string]string)
- func (ctx *ContextMock) SetLogger(logger *slog.Logger)
- func (ctx *ContextMock) SetMkdirAll(mkdirAll gotenberg.MkdirAll)
- func (ctx *ContextMock) SetPathRename(rename gotenberg.PathRename)
- func (ctx *ContextMock) SetTimeout(timeout time.Duration)
- func (ctx *ContextMock) SetValues(values map[string][]string)
- type FormData
- func (form *FormData) Bool(key string, target *bool) *FormData
- func (form *FormData) Content(filename string, target *string) *FormData
- func (form *FormData) Custom(key string, assign func(value string) error) *FormData
- func (form *FormData) Duration(key string, target *time.Duration) *FormData
- func (form *FormData) Float64(key string, target *float64) *FormData
- func (form *FormData) Inches(key string, target *float64) *FormData
- func (form *FormData) Int(key string, target *int, checks ...func(int) error) *FormData
- func (form *FormData) MandatoryBool(key string, target *bool) *FormData
- func (form *FormData) MandatoryContent(filename string, target *string) *FormData
- func (form *FormData) MandatoryCustom(key string, assign func(value string) error) *FormData
- func (form *FormData) MandatoryDuration(key string, target *time.Duration) *FormData
- func (form *FormData) MandatoryFloat64(key string, target *float64) *FormData
- func (form *FormData) MandatoryInches(key string, target *float64) *FormData
- func (form *FormData) MandatoryInt(key string, target *int, checks ...func(int) error) *FormData
- func (form *FormData) MandatoryPath(filename string, target *string) *FormData
- func (form *FormData) MandatoryPaths(extensions []string, target *[]string) *FormData
- func (form *FormData) MandatoryString(key string, target *string) *FormData
- func (form *FormData) PaperSize(key string, width, height *float64) *FormData
- func (form *FormData) Path(filename string, target *string) *FormData
- func (form *FormData) Paths(extensions []string, target *[]string) *FormData
- func (form *FormData) RejectUnknown(hint func(field, value string, file bool) string) *FormData
- func (form *FormData) Sent(key string) string
- func (form *FormData) String(key string, target *string) *FormData
- func (form *FormData) Strings(key string, target *[]string) *FormData
- func (form *FormData) Validate() error
- type HealthChecker
- type HealthCheckerMock
- type HttpError
- type Middleware
- type MiddlewarePriority
- type MiddlewareProvider
- type MiddlewareProviderMock
- type MiddlewareStack
- type Route
- type Router
- type RouterMock
- type SentinelHttpError
Examples ¶
Constants ¶
const AnswersDirectlyKey = "answersDirectly"
AnswersDirectlyKey is the echo.Context key that marks the request of a route that answers directly. See Route.AnswersDirectly.
const ArchivesFormField = "archives"
ArchivesFormField is the form field whose zip archives the Context unpacks: each entry becomes a form file, as if uploaded under "files". A zip archive uploaded under any other field stays a file.
const DownloadFromFormField = "downloadFrom"
DownloadFromFormField is the form field listing the files to download. The API reads it before the route runs.
Variables ¶
var ( // ErrContextAlreadyClosed happens when the context has been canceled. ErrContextAlreadyClosed = errors.New("context already closed") // ErrOutOfBoundsOutputPath happens when an output path is not within // context's working directory. It enforces having all the files in the // same directory. ErrOutOfBoundsOutputPath = errors.New("output path is not within context's working directory") )
var ( // ErrAsyncProcess happens when a handler or middleware handles a request // in an asynchronous fashion. ErrAsyncProcess = errors.New("async process") // ErrNoOutputFile happens when a handler or middleware has already written // the response itself, so no output file must be sent. ErrNoOutputFile = errors.New("no output file") )
Functions ¶
func ContentDisposition ¶
ContentDisposition returns the Content-Disposition header value of an attachment named filename. A name with non-ASCII characters also travels in the "filename*" parameter, percent-encoded in UTF-8, beside an ASCII "filename" fallback for the clients that read only that one. See RFC 6266, section 4.3, and RFC 8187, section 3.2.
func Max ¶
Max returns an FormData.Int check that rejects values above maximum.
func Min ¶
Min returns an FormData.Int check that rejects values below minimum.
func OneOf ¶
OneOf returns an FormData.Int check that accepts only the given values.
func PaperSizeInches ¶ added in v9.2.0
PaperSizeInches returns the width and height, in inches, portrait, of the paper size name: A3, A4, A5, B4, B5, Letter, Legal or Tabloid, in any case. ok is false for any other name.
func ParseError ¶
ParseError parses an error and returns the corresponding HTTP status and HTTP message.
func ParseInches ¶ added in v9.2.0
ParseInches converts a length to inches: a number, optionally followed by a unit, pt, px, in, mm, cm or pc, a bare number being in inches. It is the parser of FormData.Inches.
func RouteAnswersDirectly ¶
RouteAnswersDirectly reports whether the route of c writes its response itself rather than producing output files. See Route.AnswersDirectly.
func SanitizeFilename ¶ added in v9.1.0
SanitizeFilename strips path separators (including backslashes, which filepath.Base ignores on Linux) and control characters from a caller-supplied filename, then NFC-normalizes the result. This prevents a Windows-side Zip Slip when an output zip is extracted by a permissive extractor that interprets '\' as a path separator.
func WrapError ¶
func WrapError(err error, sentinel SentinelHttpError) error
WrapError wraps the given error with a SentinelHttpError. The wrapped error will be displayed in a log, while the SentinelHttpError will be sent in the response.
return api.WrapError(
// This first error will be logged.
fmt.Errorf("my action: %w", err),
// The HTTP error will be sent as a response.
api.NewSentinelHttpError(
http.StatusForbidden,
"Hey, you did something wrong!"
),
)
Types ¶
type Api ¶
type Api struct {
// contains filtered or unexported fields
}
Api is a module that provides an HTTP server. Other modules may add routes, middlewares or health checks.
func (*Api) Descriptor ¶
func (a *Api) Descriptor() gotenberg.ModuleDescriptor
Descriptor returns an Api's module descriptor.
func (*Api) Ingress ¶
func (a *Api) Ingress()
Ingress marks the API as the gotenberg.Ingress of the engines.
func (*Api) Stop ¶
Stop stops accepting requests, then waits for the synchronous ones and the asynchronous ones, such as webhook deliveries, to complete. The engines these requests use stop afterward. See gotenberg.Ingress.
type AsynchronousCounter ¶
type AsynchronousCounter interface {
AsyncCount() int64
}
AsynchronousCounter is a module interface that returns the number of active asynchronous requests.
type Context ¶
Context is the request context for a "multipart/form-data" request.
func (*Context) AddOutputPaths ¶
AddOutputPaths adds the given paths. Those paths will be used later to build the output file.
func (*Context) BuildOutputFile ¶
BuildOutputFile builds the output file according to the output paths registered in the context. If many output paths, an archive is created.
func (*Context) CreateSubDirectory ¶
CreateSubDirectory creates a subdirectory within the context's working directory.
func (*Context) FormData ¶
FormData return a FormData. Every FormData of a request records the fields it reads in the same set, which FormData.RejectUnknown checks.
func (*Context) GeneratePath ¶
GeneratePath generates a path within the context's working directory. It generates a new UUID-based filename, which drops an extension longer than 32 characters. It does not create a file.
func (*Context) GeneratePathFromFilename ¶
GeneratePathFromFilename generates a path within the context's working directory. It uses a UUID-based name on disk to avoid filesystem NAME_MAX limits but registers the given filename so that Context.OriginalFilename can resolve it. It does not create a file.
func (*Context) OriginalFilename ¶
OriginalFilename returns the original filename associated with a disk path. If no mapping exists, it falls back to filepath.Base.
func (*Context) OutputFilename ¶
OutputFilename returns the filename based on the given output path or the "Gotenberg-Output-Filename" header's value.
func (*Context) OutputHeaders ¶
OutputHeaders returns a copy of the headers Context.SetOutputHeader set.
func (*Context) RegisterDiskPath ¶
RegisterDiskPath associates a disk path with an original filename so that Context.OriginalFilename can resolve it later. It is safe for concurrent use.
func (*Context) Rename ¶
Rename is just a wrapper around os.Rename, as we need to mock this behavior in our tests.
func (*Context) Request ¶
Request returns the http.Request.
func (*Context) SetOutputHeader ¶
SetOutputHeader sets a header that describes the output, such as the outcome of a remediation. It goes with the output file, on the response or on the webhook request. Like Context.AddOutputPaths, it is not safe for concurrent use.
type ContextMock ¶
type ContextMock struct {
*Context
}
ContextMock is a helper for tests.
ctx := &api.ContextMock{Context: &api.Context{}}
func (*ContextMock) DirPath ¶
func (ctx *ContextMock) DirPath() string
DirPath returns the context's working directory path.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetDirPath("/foo")
dirPath := ctx.DirPath()
func (*ContextMock) OutputPaths ¶
func (ctx *ContextMock) OutputPaths() []string
OutputPaths returns the registered output paths.
ctx := &api.ContextMock{Context: &api.Context{}}
outputPaths := ctx.OutputPaths()
func (*ContextMock) SetCancelled ¶
func (ctx *ContextMock) SetCancelled(cancelled bool)
SetCancelled sets if the context is canceled or not.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetCancelled(true)
func (*ContextMock) SetDirPath ¶
func (ctx *ContextMock) SetDirPath(path string)
SetDirPath sets the context's working directory path.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetDirPath("/foo")
func (*ContextMock) SetEchoContext ¶
func (ctx *ContextMock) SetEchoContext(c *echo.Context)
SetEchoContext sets the echo.Context.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.setEchoContext(c)
func (*ContextMock) SetFileFields ¶
func (ctx *ContextMock) SetFileFields(fields ...string)
SetFileFields sets the multipart fields the files arrived under.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetFileFields("files", "watermark")
func (*ContextMock) SetFiles ¶
func (ctx *ContextMock) SetFiles(files map[string]string)
SetFiles sets the files.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetFiles(map[string]string{
"foo": "/foo",
})
func (*ContextMock) SetLogger ¶
func (ctx *ContextMock) SetLogger(logger *slog.Logger)
SetLogger sets the logger.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetLogger(slog.Default())
func (*ContextMock) SetMkdirAll ¶
func (ctx *ContextMock) SetMkdirAll(mkdirAll gotenberg.MkdirAll)
SetMkdirAll sets the gotenberg.MkdirAll.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetMkdirAll(mkdirAll)
func (*ContextMock) SetPathRename ¶
func (ctx *ContextMock) SetPathRename(rename gotenberg.PathRename)
SetPathRename sets the gotenberg.PathRename.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.setPathRename(rename)
func (*ContextMock) SetTimeout ¶
func (ctx *ContextMock) SetTimeout(timeout time.Duration)
SetTimeout sets the time limit of the request.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetTimeout(30 * time.Second)
func (*ContextMock) SetValues ¶
func (ctx *ContextMock) SetValues(values map[string][]string)
SetValues sets the values.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetValues(map[string][]string{
"url": {
"foo",
},
})
type FormData ¶
type FormData struct {
// contains filtered or unexported fields
}
FormData is a helper for validating and hydrating values from a "multipart/form-data" request.
form := ctx.FormData()
func JSON ¶
JSON binds a JSON form field to a variable. It populates an error if the value does not unmarshal into it, which want describes the expected value for. An absent or empty field keeps the variable's current value.
foo := []int{404}
api.JSON(ctx.FormData(), "foo", &foo, "a JSON array of status codes, such as [499,599]")
func (*FormData) Bool ¶
Bool binds a form field to a bool variable. It populates an error if the value is not bool. An absent or empty field keeps the variable's current value.
foo := true
ctx.FormData().Bool("foo", &foo)
func (*FormData) Content ¶
Content binds the content of a form data file to a string variable. An absent file keeps the variable's current value.
content := "bar"
ctx.FormData().Content("foo.txt", &content)
func (*FormData) Custom ¶
Custom helps to define a custom binding function for a form field. The error assign returns follows the value in the message, as in "form field 'foo' is invalid (got 'bar', want a JSON object)": it states what the field wants, or why the value is wrong.
var foo map[string]string
ctx.FormData().Custom("foo", func(value string) error {
if value == "" {
foo = map[string]string{"bar": "baz"}
return nil
}
err := json.Unmarshal([]byte(value), &foo)
if err != nil {
return errors.New("want a JSON object")
}
return nil
})
func (*FormData) Duration ¶
Duration binds a form field to a time.Duration variable. It populates an error if the value is not time.Duration. An absent or empty field keeps the variable's current value.
foo := 2 * time.Second
ctx.FormData().Duration("foo", &foo)
func (*FormData) Float64 ¶
Float64 binds a form field to a float64 variable. It populates an error if the value is not a finite float64. An absent or empty field keeps the variable's current value.
foo := 2.0
ctx.FormData().Float64("foo", &foo)
func (*FormData) Inches ¶
Inches binds a form field to a float64 variable, in inches. The value is a number, optionally suffixed by a unit: pt, px, in, mm, cm or pc. It populates an error if the value cannot be converted to inches. An absent or empty field keeps the variable's current value.
foo := 2.0
ctx.FormData().Inches("foo", &foo)
func (*FormData) Int ¶
Int binds a form field to an int variable. It populates an error if the value is not int, or if one of the checks rejects it. An absent or empty field keeps the variable's current value.
foo := 2
ctx.FormData().Int("foo", &foo, api.Min(1))
func (*FormData) MandatoryBool ¶
MandatoryBool binds a form field to a bool variable. It populates an error if the value is not bool, is empty, or the "key" does not exist.
var foo bool
ctx.FormData().MandatoryBool("foo", &foo)
func (*FormData) MandatoryContent ¶
MandatoryContent binds the content of a form data file to a string variable. It populates an error if the file does not exist.
var content string
ctx.FormData().MandatoryContent("foo.txt", &content)
func (*FormData) MandatoryCustom ¶
MandatoryCustom helps to define a custom binding function for a form field. It populates an error if the value is empty or the "key" does not exist. The error assign returns follows the value in the message, as with FormData.Custom.
var foo map[string]string
ctx.FormData().MandatoryCustom("foo", func(value string) error {
err := json.Unmarshal([]byte(value), &foo)
if err != nil {
return errors.New("want a JSON object")
}
return nil
})
func (*FormData) MandatoryDuration ¶
MandatoryDuration binds a form field to a time.Duration variable. It populates an error if the value is not time.Duration, is empty, or the "key" does not exist.
var foo time.Duration
ctx.FormData().MandatoryDuration("foo", &foo)
func (*FormData) MandatoryFloat64 ¶
MandatoryFloat64 binds a form field to a float64 variable. It populates an error if the value is not a finite float64, is empty, or the "key" does not exist.
var foo float64
ctx.FormData().MandatoryFloat64("foo", &foo)
func (*FormData) MandatoryInches ¶
MandatoryInches binds a form field to a float64 variable, in inches. It populates an error if the value cannot be converted to inches, is empty, or the "key" does not exist.
var foo float64
ctx.FormData().MandatoryInches("foo", &foo)
func (*FormData) MandatoryInt ¶
MandatoryInt binds a form field to an int variable. It populates an error if the value is not int, if one of the checks rejects it, if it is empty, or if the "key" does not exist.
var foo int
ctx.FormData().MandatoryInt("foo", &foo, api.OneOf(1, 2))
func (*FormData) MandatoryPath ¶
MandatoryPath binds the absolute path of a form data file to a string variable. It populates an error if the file does not exist.
var path string
ctx.FormData().MandatoryPath("foo.txt", &path)
func (*FormData) MandatoryPaths ¶
MandatoryPaths binds the absolute paths of form data files, according to a list of file extensions, to a string slice variable. It populates an error if there is no file for given file extensions.
var paths []string
ctx.FormData().MandatoryPaths([]string{".txt"}, &paths)
func (*FormData) MandatoryString ¶
MandatoryString binds a form field to a string variable. It populates an error if the value is empty or the "key" does not exist.
var foo string
ctx.FormData().MandatoryString("foo", &foo)
func (*FormData) PaperSize ¶
PaperSize binds the width and height, in inches, of the paper size a form field names: A3, A4, A5, B4, B5, Letter, Legal or Tabloid, in any case. It leaves the targets untouched when the field is empty, and populates an error for an unknown name.
var width, height float64
ctx.FormData().PaperSize("paperSize", &width, &height)
func (*FormData) Path ¶
Path binds the absolute path of a form data file to a string variable.
var path string
ctx.FormData().Path("foo.txt", &path)
func (*FormData) Paths ¶
Paths bind the absolute paths of form data files, according to a list of file extensions, to a string slice variable.
var paths []string
ctx.FormData().Paths([]string{".txt"}, &paths)
func (*FormData) RejectUnknown ¶
RejectUnknown populates an error for every value form field no binding of the request read so far, so that a misspelled or removed field answers 400 rather than being ignored. Call it last, once the route has bound every field it takes, then call FormData.Validate. downloadFrom, which the API reads before the route runs, is never unknown.
hint returns how to fix a field, such as the field or the stage that replaced one of an earlier major version, or "" for none. value is the field's first value, which the fix may name, and "" for a file field. file tells a file field, the multipart field files arrived under, from a value field. Routes read files by filename, whatever field they arrive under, so a file field is rejected only when hint returns a fix for it. A nil hint gives none, and rejects no file field.
err := form.
MandatoryString("url", &url).
RejectUnknown(nil).
Validate()
func (*FormData) Sent ¶
Sent returns the first value of the value form field key as the client sent it, or "" when absent, without binding it: FormData.RejectUnknown still rejects a field only Sent read. A hint reads the other fields its fix depends on with it.
func (*FormData) String ¶
String binds a form field to a string variable. An absent or empty field keeps the variable's current value.
foo := "bar"
ctx.FormData().String("foo", &foo)
type HealthChecker ¶
type HealthChecker interface {
Checks() ([]health.CheckerOption, error)
// Ready blocks until the module is ready, or until ctx is done.
Ready(ctx context.Context) error
}
HealthChecker is a module interface that allows adding health checks to the API.
See https://github.com/alexliesenfeld/health for more details.
type HealthCheckerMock ¶
type HealthCheckerMock struct {
ChecksMock func() ([]health.CheckerOption, error)
ReadyMock func(ctx context.Context) error
}
HealthCheckerMock is a mock for the HealthChecker interface.
func (*HealthCheckerMock) Checks ¶
func (mod *HealthCheckerMock) Checks() ([]health.CheckerOption, error)
Checks calls ChecksMock.
type Middleware ¶
type Middleware struct {
// Stack tells in which stack the middleware should be located.
// Default to [DefaultStack].
// Optional.
Stack MiddlewareStack
// Priority tells if the middleware should be positioned high or not in
// its stack.
// Default to [VeryLowPriority].
// Optional.
Priority MiddlewarePriority
// Handler is the function of the middleware.
// Required.
Handler echo.MiddlewareFunc
}
Middleware is a middleware that can be added to the Api's middlewares chain.
middleware := Middleware{
Handler: func() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
rootPath := c.Get("rootPath").(string)
healthURI := fmt.Sprintf("%shealth", rootPath)
// Skip the middleware if health check URI.
if c.Request().RequestURI == healthURI {
// Call the next middleware in the chain.
return next(c)
}
// Your middleware process.
// ...
// Call the next middleware in the chain.
return next(c)
}
}
}(),
}
type MiddlewarePriority ¶
type MiddlewarePriority uint32
MiddlewarePriority is a type that helps to determine the execution order of middlewares provided by the MiddlewareProvider modules in a stack.
const ( VeryLowPriority MiddlewarePriority = iota LowPriority MediumPriority HighPriority VeryHighPriority )
The priorities, from the last middleware of a stack to run to the first.
type MiddlewareProvider ¶
type MiddlewareProvider interface {
Middlewares() ([]Middleware, error)
}
MiddlewareProvider is a module interface that adds middlewares to the Api.
type MiddlewareProviderMock ¶
type MiddlewareProviderMock struct {
MiddlewaresMock func() ([]Middleware, error)
}
MiddlewareProviderMock is a mock for the MiddlewareProvider interface.
func (*MiddlewareProviderMock) Middlewares ¶
func (provider *MiddlewareProviderMock) Middlewares() ([]Middleware, error)
Middlewares calls MiddlewaresMock.
type MiddlewareStack ¶
type MiddlewareStack uint32
MiddlewareStack is a type that helps to determine in which stack the middlewares provided by the MiddlewareProvider modules should be located.
const ( // DefaultStack runs the middleware after routing, on every route. DefaultStack MiddlewareStack = iota // PreRouterStack runs the middleware before routing, on every request. PreRouterStack // MultipartStack runs the middleware on the multipart/form-data routes // only, after the [Context] is built. MultipartStack )
type Route ¶
type Route struct {
// Method is the HTTP method of the route (i.e., GET, POST, etc.).
// Required.
Method string
// Path is the sub path of the route. Must start with a slash.
// Required.
Path string
// IsMultipart tells if the route is "multipart/form-data".
// Optional.
IsMultipart bool
// DisableTelemetry disables telemetry (logging, tracing, metrics) for
// this route.
// Optional.
DisableTelemetry bool
// AnswersDirectly tells that a multipart route writes its response
// itself, such as JSON, rather than producing output files. Middlewares
// that deliver output files elsewhere, such as the webhook, read it with
// [RouteAnswersDirectly] to refuse the request before it runs.
// Optional.
AnswersDirectly bool
// Handler is the function that handles the request.
// Required.
Handler echo.HandlerFunc
}
Route represents a route from a Router.
type RouterMock ¶
RouterMock is a mock for the Router interface.
func (*RouterMock) Routes ¶
func (router *RouterMock) Routes() ([]Route, error)
Routes calls RoutesMock.
type SentinelHttpError ¶
type SentinelHttpError struct {
// contains filtered or unexported fields
}
SentinelHttpError is the HTTP sidekick of an error.
func NewSentinelHttpError ¶
func NewSentinelHttpError(status int, message string) SentinelHttpError
NewSentinelHttpError creates a SentinelHttpError. The message will be sent as the response's body if returned from a handler, so make sure to not leak sensible information.
func (SentinelHttpError) Error ¶
func (err SentinelHttpError) Error() string
Error returns the message.
func (SentinelHttpError) HttpError ¶
func (err SentinelHttpError) HttpError() (int, string)
HttpError returns the status and message.