api

package
v9.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 46 Imported by: 0

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

Examples

Constants

View Source
const AnswersDirectlyKey = "answersDirectly"

AnswersDirectlyKey is the echo.Context key that marks the request of a route that answers directly. See Route.AnswersDirectly.

View Source
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.

View Source
const DownloadFromFormField = "downloadFrom"

DownloadFromFormField is the form field listing the files to download. The API reads it before the route runs.

Variables

View Source
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")
)
View Source
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

func ContentDisposition(filename string) string

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

func Max(maximum int) func(int) error

Max returns an FormData.Int check that rejects values above maximum.

func Min

func Min(minimum int) func(int) error

Min returns an FormData.Int check that rejects values below minimum.

func OneOf

func OneOf(values ...int) func(int) error

OneOf returns an FormData.Int check that accepts only the given values.

func OrList

func OrList(values []string) string

OrList joins values for an error message: "a", "a or b", "a, b or c".

func PaperSizeInches added in v9.2.0

func PaperSizeInches(name string) (width, height float64, ok bool)

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

func ParseError(err error) (int, string)

ParseError parses an error and returns the corresponding HTTP status and HTTP message.

func ParseInches added in v9.2.0

func ParseInches(value string) (float64, error)

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

func RouteAnswersDirectly(c *echo.Context) bool

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

func SanitizeFilename(name string) string

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) Provision

func (a *Api) Provision(ctx *gotenberg.Context) error

Provision sets the module properties.

func (*Api) Report

func (a *Api) Report() gotenberg.Report

Report describes the address the API listens on, and its authentication.

func (*Api) Start

func (a *Api) Start() error

Start starts the HTTP server.

func (*Api) Stop

func (a *Api) Stop(ctx context.Context) error

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.

func (*Api) Validate

func (a *Api) Validate() error

Validate validates the module properties.

type AsynchronousCounter

type AsynchronousCounter interface {
	AsyncCount() int64
}

AsynchronousCounter is a module interface that returns the number of active asynchronous requests.

See https://github.com/gotenberg/gotenberg/issues/1022.

type Context

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

Context is the request context for a "multipart/form-data" request.

func (*Context) AddOutputPaths

func (ctx *Context) AddOutputPaths(paths ...string) error

AddOutputPaths adds the given paths. Those paths will be used later to build the output file.

func (*Context) BuildOutputFile

func (ctx *Context) BuildOutputFile() (string, error)

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

func (ctx *Context) CreateSubDirectory(dirName string) (string, error)

CreateSubDirectory creates a subdirectory within the context's working directory.

func (*Context) DirPath

func (ctx *Context) DirPath() string

DirPath returns the path to the request's working directory.

func (*Context) FileCount

func (ctx *Context) FileCount() int

FileCount returns the number of files received in the request.

func (*Context) FormData

func (ctx *Context) FormData() *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

func (ctx *Context) GeneratePath(extension string) string

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

func (ctx *Context) GeneratePathFromFilename(filename string) string

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) Log

func (ctx *Context) Log() *slog.Logger

Log returns the context slog.Logger.

func (*Context) OriginalFilename

func (ctx *Context) OriginalFilename(diskPath string) string

OriginalFilename returns the original filename associated with a disk path. If no mapping exists, it falls back to filepath.Base.

func (*Context) OutputFilename

func (ctx *Context) OutputFilename(outputPath string) string

OutputFilename returns the filename based on the given output path or the "Gotenberg-Output-Filename" header's value.

func (*Context) OutputHeaders

func (ctx *Context) OutputHeaders() map[string]string

OutputHeaders returns a copy of the headers Context.SetOutputHeader set.

func (*Context) RegisterDiskPath

func (ctx *Context) RegisterDiskPath(diskPath, originalFilename string)

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

func (ctx *Context) Rename(oldpath, newpath string) error

Rename is just a wrapper around os.Rename, as we need to mock this behavior in our tests.

func (*Context) Request

func (ctx *Context) Request() *http.Request

Request returns the http.Request.

func (*Context) SetOutputHeader

func (ctx *Context) SetOutputHeader(key, value string)

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.

func (*Context) Timeout

func (ctx *Context) Timeout() time.Duration

Timeout returns the time limit of the request, that is --api-timeout (env API_TIMEOUT), or zero when it is unknown. Routes use it to refuse a value, such as a delay, that cannot fit in it.

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

func JSON[T any](form *FormData, key string, target *T, want string) *FormData

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

func (form *FormData) Bool(key string, target *bool) *FormData

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

func (form *FormData) Content(filename string, target *string) *FormData

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

func (form *FormData) Custom(key string, assign func(value string) error) *FormData

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

func (form *FormData) Duration(key string, target *time.Duration) *FormData

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

func (form *FormData) Float64(key string, target *float64) *FormData

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

func (form *FormData) Inches(key string, target *float64) *FormData

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

func (form *FormData) Int(key string, target *int, checks ...func(int) error) *FormData

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

func (form *FormData) MandatoryBool(key string, target *bool) *FormData

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

func (form *FormData) MandatoryContent(filename string, target *string) *FormData

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

func (form *FormData) MandatoryCustom(key string, assign func(value string) error) *FormData

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

func (form *FormData) MandatoryDuration(key string, target *time.Duration) *FormData

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

func (form *FormData) MandatoryFloat64(key string, target *float64) *FormData

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

func (form *FormData) MandatoryInches(key string, target *float64) *FormData

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

func (form *FormData) MandatoryInt(key string, target *int, checks ...func(int) error) *FormData

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

func (form *FormData) MandatoryPath(filename string, target *string) *FormData

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

func (form *FormData) MandatoryPaths(extensions []string, target *[]string) *FormData

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

func (form *FormData) MandatoryString(key string, target *string) *FormData

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

func (form *FormData) PaperSize(key string, width, height *float64) *FormData

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

func (form *FormData) Path(filename string, target *string) *FormData

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

func (form *FormData) Paths(extensions []string, target *[]string) *FormData

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

func (form *FormData) RejectUnknown(hint func(field, value string, file bool) string) *FormData

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

func (form *FormData) Sent(key string) string

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

func (form *FormData) String(key string, target *string) *FormData

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)

func (*FormData) Strings

func (form *FormData) Strings(key string, target *[]string) *FormData

Strings binds every value submitted for key, in submission order. A field repeated in the multipart body (e.g. multiple "stampSource") contributes one entry per occurrence, which lets a route read parallel field arrays.

func (*FormData) Validate

func (form *FormData) Validate() error

Validate returns nil or an error related to the FormData values, with a SentinelHttpError (status code 400, errors' details as a message) wrapped inside.

var foo string

err := ctx.FormData().
   MandatoryString("foo", &foo).
   Validate()

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.

func (*HealthCheckerMock) Ready

func (mod *HealthCheckerMock) Ready(ctx context.Context) error

Ready calls ReadyMock.

type HttpError

type HttpError interface {
	HttpError() (int, string)
}

HttpError is an interface allowing to retrieve the HTTP details of an error.

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 Router

type Router interface {
	Routes() ([]Route, error)
}

Router is a module interface that adds routes to the Api.

type RouterMock

type RouterMock struct {
	RoutesMock func() ([]Route, error)
}

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.

Jump to

Keyboard shortcuts

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