api

package
v7.4.3 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2022 License: MIT Imports: 28 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

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

func (API) Descriptor() gotenberg.ModuleDescriptor

Descriptor returns an API's module descriptor.

func (API) GraceDuration

func (a API) GraceDuration() time.Duration

GraceDuration updates the expiration time of files and directories parsed by the gc.GarbageCollector.

func (*API) Provision

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

Provision sets the module properties.

func (*API) Start

func (a *API) Start() error

Start starts the HTTP server.

func (API) StartupMessage

func (a API) StartupMessage() string

StartupMessage returns a custom startup message.

func (API) Stop

func (a API) Stop(ctx context.Context) error

Stop stops the HTTP server.

func (API) Validate

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 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 data value 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 data value.

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 data value to a time.Duration variable. It populates an error if the form data value 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 data value 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 data value 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 data value 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 data value. 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 data value 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 data value 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 data value 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 data value 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 data value 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 GarbageCollectorGraceDurationIncrementer added in v7.1.0

type GarbageCollectorGraceDurationIncrementer interface {
	AddGraceDuration() time.Duration
}

GarbageCollectorGraceDurationIncrementer is a module interface for increasing the grace duration provided by the API for the garbage collector.

type HTTPError

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

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

type HealthChecker

type HealthChecker interface {
	Checks() ([]health.CheckerOption, error)
}

HealthChecker is a module interface which allows adding health checks to the API.

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

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 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 MockContext

type MockContext struct {
	*Context
}

MockContext is a helper for tests.

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

func (MockContext) OutputPaths

func (ctx MockContext) OutputPaths() []string

OutputPaths returns the registered output paths.

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

func (*MockContext) SetCancelled

func (ctx *MockContext) SetCancelled(cancelled bool)

SetCancelled sets if the context is cancelled or not.

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

func (*MockContext) SetDirPath

func (ctx *MockContext) SetDirPath(path string)

SetDirPath sets the context's working directory path.

ctx := &api.MockContext{Context: &api.Context{}}
ctx.SetDirPath("/foo")

func (*MockContext) SetEchoContext added in v7.1.0

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

SetEchoContext sets the echo.Context.

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

func (*MockContext) SetFiles

func (ctx *MockContext) SetFiles(files map[string]string)

SetFiles sets the files.

ctx := &api.MockContext{Context: &api.Context{}}
ctx.SetFiles(map[string]string{
  "foo": "/foo",
})

func (*MockContext) SetLogger added in v7.1.0

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

SetLogger sets the logger.

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

func (*MockContext) SetValues

func (ctx *MockContext) SetValues(values map[string][]string)

SetValues sets the values.

ctx := &api.MockContext{Context: &api.Context{}}
ctx.SetValues(map[string][]string{
  "url": {
    "foo",
  },
})

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