Documentation
¶
Overview ¶
Package api provides a module, which is an HTTP server. Other modules may add multipart/form-data routes, middlewares, and health checks.
Index ¶
- Constants
- Variables
- func ParseError(err error) (int, 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) FormData() *FormData
- func (ctx *Context) GeneratePath(extension string) string
- func (ctx *Context) GeneratePathFromFilename(filename string) string
- func (ctx *Context) Log() *zap.Logger
- func (ctx *Context) OutputFilename(outputPath string) string
- func (ctx *Context) Rename(oldpath, newpath string) error
- func (ctx *Context) Request() *http.Request
- 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) SetFiles(files map[string]string)
- func (ctx *ContextMock) SetLogger(logger *zap.Logger)
- func (ctx *ContextMock) SetMkdirAll(mkdirAll gotenberg.MkdirAll)
- func (ctx *ContextMock) SetPathRename(rename gotenberg.PathRename)
- func (ctx *ContextMock) SetValues(values map[string][]string)
- type FormData
- func (form *FormData) Bool(key string, target *bool, defaultValue bool) *FormData
- func (form *FormData) Content(filename string, target *string, defaultValue string) *FormData
- func (form *FormData) Custom(key string, assign func(value string) error) *FormData
- func (form *FormData) Duration(key string, target *time.Duration, defaultValue time.Duration) *FormData
- func (form *FormData) Embeds(target *[]string) *FormData
- func (form *FormData) Float64(key string, target *float64, defaultValue float64) *FormData
- func (form *FormData) Inches(key string, target *float64, defaultValue float64) *FormData
- func (form *FormData) Int(key string, target *int, defaultValue int) *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) *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) Path(filename string, target *string) *FormData
- func (form *FormData) Paths(extensions []string, target *[]string) *FormData
- func (form *FormData) String(key string, target *string, defaultValue 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
Constants ¶
const (
EmbedsFormField string = "embeds"
)
EmbedsFormField represents the form field name for embedding files.
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 handles a request // without sending any output file. ErrNoOutputFile = errors.New("no output file") )
Functions ¶
func ParseError ¶
ParseError parses an error and returns the corresponding HTTP status and HTTP message.
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) StartupMessage ¶
StartupMessage returns a custom startup message.
type AsynchronousCounter ¶ added in v8.21.0
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" requests.
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 ¶ added in v8.15.0
CreateSubDirectory creates a subdirectory within the context's working directory.
func (*Context) GeneratePath ¶
GeneratePath generates a path within the context's working directory. It generates a new UUID-based filename. It does not create a file.
func (*Context) GeneratePathFromFilename ¶ added in v8.21.0
GeneratePathFromFilename generates a path within the context's working directory, using the given filename (with extension). It does not create a file.
func (*Context) OutputFilename ¶
OutputFilename returns the filename based on the given output path or the "Gotenberg-Output-Filename" header's value.
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) 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 *zap.Logger)
SetLogger sets the logger.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetLogger(zap.NewNop())
func (*ContextMock) SetMkdirAll ¶ added in v8.15.0
func (ctx *ContextMock) SetMkdirAll(mkdirAll gotenberg.MkdirAll)
SetMkdirAll sets the gotenberg.MkdirAll.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetMkdirAll(mkdirAll)
func (*ContextMock) SetPathRename ¶ added in v8.2.2
func (ctx *ContextMock) SetPathRename(rename gotenberg.PathRename)
SetPathRename sets the gotenberg.PathRename.
ctx := &api.ContextMock{Context: &api.Context{}}
ctx.setPathRename(rename)
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 (*FormData) Bool ¶
Bool binds a form field to a bool variable. It populates an error if the value is not bool.
var foo bool
ctx.FormData().Bool("foo", &foo, true)
func (*FormData) Content ¶
Content binds the content of a form data file to a string variable.
var content string
ctx.FormData().Content("foo.txt", &content, "bar")
func (*FormData) Custom ¶
Custom helps to define a custom binding function for a form field.
var foo map[string]string
ctx.FormData().Custom("foo", func(value string) error {
if value == "" {
foo = "bar"
return nil
}
err := json.Unmarshal([]byte(value), &foo)
if err != nil {
return fmt.Errorf("unmarshal foo: %w", err)
}
return nil
})
func (*FormData) Duration ¶
func (form *FormData) Duration(key string, target *time.Duration, defaultValue time.Duration) *FormData
Duration binds a form field to a time.Duration variable. It populates an error if the form field is not time.Duration.
var foo time.Duration
ctx.FormData().Duration("foo", &foo, time.Duration(2) * time.Second)
func (*FormData) Embeds ¶ added in v8.25.0
Embeds binds the absolute paths of form data files that should be embedded in the PDF. Only files uploaded with the "embeds" field name will be included.
var embeds []string ctx.FormData().Embeds(&embeds)
func (*FormData) Float64 ¶
Float64 binds a form field to a float64 variable. It populates an error if the value is not float64.
var foo float64
ctx.FormData().Float64("foo", &foo, 2.0)
func (*FormData) Inches ¶ added in v8.3.0
Inches bind a form field to a float64 variable. It populates an error if the value cannot be computed back to inches.
var foo float64
ctx.FormData().Inches("foo", &foo, 2.0)
func (*FormData) Int ¶
Int binds a form field to an int variable. It populates an error if the value is not int.
var foo int
ctx.FormData().Int("foo", &foo, 2)
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.
var foo map[string]string
ctx.FormData().MandatoryCustom("foo", func(value string) error {
err := json.Unmarshal([]byte(value), &foo)
if err != nil {
return fmt.Errorf("unmarshal foo: %w", err)
}
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, or 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 float64, is empty, or the "key" does not exist.
var foo float64
ctx.FormData().MandatoryFloat64("foo", &foo)
func (*FormData) MandatoryInches ¶ added in v8.3.0
MandatoryInches binds a form field to a float64 variable. It populates an error if the value cannot be computed back 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, or is empty, or the "key" does not exist.
var foo int
ctx.FormData().MandatoryInt("foo", &foo)
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) 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) String ¶
String binds a form field to a string variable.
var foo string
ctx.FormData().String("foo", &foo, "bar")
func (*FormData) Validate ¶
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, "bar").
Validate()
type HealthChecker ¶
type HealthChecker interface {
Checks() ([]health.CheckerOption, error)
Ready() 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() error
}
HealthCheckerMock is a mock for the HealthChecker interface.
func (*HealthCheckerMock) Checks ¶
func (mod *HealthCheckerMock) Checks() ([]health.CheckerOption, error)
func (*HealthCheckerMock) Ready ¶
func (mod *HealthCheckerMock) Ready() 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 )
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)
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 MiddlewareStack = iota PreRouterStack 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
// DisableLogging disables the logging for this route.
// Optional.
DisableLogging 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)
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.