api

package
v7.10.2 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2023 License: MIT Imports: 24 Imported by: 2

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

This section is empty.

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 = errors.New("async process")

ErrAsyncProcess happens when a handler or middleware handles a request in an asynchronous fashion.

Functions

func ParseError added in v7.1.0

func ParseError(err error) (int, string)

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 added in v7.10.0

type Api struct {
	// contains filtered or unexported fields
}

Api is a module which provides an HTTP server. Other modules may add routes, middlewares or health checks.

func (*Api) Descriptor added in v7.10.0

func (a *Api) Descriptor() gotenberg.ModuleDescriptor

Descriptor returns an Api's module descriptor.

func (*Api) Provision added in v7.10.0

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

Provision sets the module properties.

func (*Api) Start added in v7.10.0

func (a *Api) Start() error

Start starts the HTTP server.

func (*Api) StartupMessage added in v7.10.0

func (a *Api) StartupMessage() string

StartupMessage returns a custom startup message.

func (*Api) Stop added in v7.10.0

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

Stop stops the HTTP server.

func (*Api) Validate added in v7.10.0

func (a *Api) Validate() error

Validate validates the module properties.

type Context

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

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

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 added in v7.1.0

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

func (ctx *Context) FormData() *FormData

FormData return a FormData.

func (*Context) GeneratePath

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

GeneratePath generates a path within the context's working directory. It does not create a file.

func (*Context) Log

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

Log returns the context zap.Logger.

func (*Context) OutputFilename added in v7.1.0

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

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

Request returns the http.Request.

type ContextMock added in v7.5.1

type ContextMock struct {
	*Context
}

ContextMock is a helper for tests.

ctx := &api.ContextMock{Context: &api.Context{}}

func (*ContextMock) DirPath added in v7.10.0

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 added in v7.5.1

func (ctx *ContextMock) OutputPaths() []string

OutputPaths returns the registered output paths.

ctx := &api.ContextMock{Context: &api.Context{}}
outputPaths := ctx.OutputPaths()

func (*ContextMock) SetCancelled added in v7.5.1

func (ctx *ContextMock) SetCancelled(cancelled bool)

SetCancelled sets if the context is cancelled or not.

ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetCancelled(true)

func (*ContextMock) SetDirPath added in v7.5.1

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 added in v7.5.1

func (ctx *ContextMock) SetEchoContext(c echo.Context)

SetEchoContext sets the echo.Context.

ctx := &api.ContextMock{Context: &api.Context{}}
ctx.setEchoContext(c)

func (*ContextMock) SetFiles added in v7.5.1

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 added in v7.5.1

func (ctx *ContextMock) SetLogger(logger *zap.Logger)

SetLogger sets the logger.

ctx := &api.ContextMock{Context: &api.Context{}}
ctx.SetLogger(zap.NewNop())

func (*ContextMock) SetValues added in v7.5.1

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

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

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

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

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

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

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

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

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

func (form *FormData) Int(key string, target *int, defaultValue int) *FormData

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

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.

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

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 is not float64, is empty, or the "key" does not exist.

var foo float64

ctx.FormData().MandatoryFloat64("foo", &foo)

func (*FormData) MandatoryInt

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

MandatoryInt binds a form field to an int variable. It populates an error if the value is not int, is empty, or the "key" does not exist.

var foo int

ctx.FormData().MandatoryInt("foo", &foo)

func (*FormData) MandatoryPath

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

MandatoryPath binds the absolute path ofa 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) 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 binds 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

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

String binds a form field to a string variable.

var foo string

ctx.FormData().String("foo", &foo, "bar")

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 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 which allows adding health checks to the API.

See https://github.com/alexliesenfeld/health for more details.

type HealthCheckerMock added in v7.10.0

type HealthCheckerMock struct {
	ChecksMock func() ([]health.CheckerOption, error)
	ReadyMock  func() error
}

HealthCheckerMock is mock for the HealthChecker interface.

func (*HealthCheckerMock) Checks added in v7.10.0

func (mod *HealthCheckerMock) Checks() ([]health.CheckerOption, error)

func (*HealthCheckerMock) Ready added in v7.10.2

func (mod *HealthCheckerMock) Ready() error

type HttpError added in v7.10.0

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 which 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 which 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 which adds middlewares to the Api.

type MiddlewareProviderMock added in v7.10.0

type MiddlewareProviderMock struct {
	MiddlewaresMock func() ([]Middleware, error)
}

MiddlewareProviderMock is a mock for the MiddlewareProvider interface.

func (*MiddlewareProviderMock) Middlewares added in v7.10.0

func (provider *MiddlewareProviderMock) Middlewares() ([]Middleware, error)

type MiddlewareStack added in v7.1.0

type MiddlewareStack uint32

MiddlewareStack is a type which helps to determine in which stack the middlewares provided by the MiddlewareProvider modules should be located.

const (
	DefaultStack MiddlewareStack = iota
	PreRouterStack
	MultipartStack
)

type Route added in v7.1.0

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 which handles the request.
	// Required.
	Handler echo.HandlerFunc
}

Route represents a route from a Router.

type Router added in v7.1.0

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

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

type RouterMock added in v7.10.0

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

RouterMock is a mock for the Router interface.

func (*RouterMock) Routes added in v7.10.0

func (router *RouterMock) Routes() ([]Route, error)

type SentinelHttpError added in v7.10.0

type SentinelHttpError struct {
	// contains filtered or unexported fields
}

SentinelHttpError is the HTTP sidekick of an error.

func NewSentinelHttpError added in v7.10.0

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 added in v7.10.0

func (err SentinelHttpError) Error() string

Error returns the message.

func (SentinelHttpError) HttpError added in v7.10.0

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