api

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2022 License: MIT Imports: 15 Imported by: 2

Documentation

Overview

Package api is a standalone API package/pattern built on echo and logrus. It sets up /statusz and /healthz endpoints, and sets up logging middleware that takes care of the following important, and fundamentally (in Go) interconnected tasks:

  • Extract (or add) a trace ID header to the request and response.
  • The trace ID can be retrieved through api.TraceID(context) of the echo.Context for the request.
  • Use that trace ID header as context for the logrus logger.
  • Handle request logging (metadata about the request and response, and log at the level appropriate for the status code).
  • The request logger can be retrieved api.Logger(echo.Context).
  • Recover from panics.
  • Coerce all errors into api.Error types, and marshal them.
  • Override echo's HTTPErrorHandler to pass through api.Error types.

Index

Constants

View Source
const HealthPath = "/healthz"
View Source
const StatusPath = "/statusz"
View Source
const TraceIdHeader = "Trace-Id"

Variables

This section is empty.

Functions

func HTTPErrorHandler deprecated

func HTTPErrorHandler(err error, c echo.Context)

Deprecated: Use NewHTTPErrorHandler instead.

func Logger

func Logger(c echo.Context) *logrus.Entry

func LoggingMiddleware

func LoggingMiddleware(outerLogger *logrus.Entry) echo.MiddlewareFunc

func LoggingMiddlewareDefaultDoLog

func LoggingMiddlewareDefaultDoLog(c echo.Context, logger *logrus.Entry)

func LoggingMiddlewareWithConfig

func LoggingMiddlewareWithConfig(outerLogger *logrus.Entry, cfg LoggingMiddlwareConfig) echo.MiddlewareFunc

func New

func New(cfg Config) *echo.Echo

func NewHTTPErrorHandler

func NewHTTPErrorHandler(e *echo.Echo) echo.HTTPErrorHandler

func SetCacheControl

func SetCacheControl(c echo.Context)

SetCacheControl sets the Cache-Control header to the given value, if it was configured in WithCacheControl. Because response headers must be written before the body is written, we cannot handle this like normal middleware, and write the header after handling the call. Yet, we do not want to write the header in the case of error, so the endpoint itself MUST write the cache-control header. Thus, we can configure middleware, and call CacheControl unconditionally in our handlers, but it will noop if not configured.

func SetLogger

func SetLogger(c echo.Context, logger *logrus.Entry)

func StdContext

func StdContext(c echo.Context) context.Context

StdContext returns a standard context from an echo context. Useful when you are in an endpoint, and want to call into some code that shouldn't use echo, but you still want to pass along the original endpoint's context so you can get stuff back out of it (like a logger). This uses the logctx package to set the expected values in the context, so the echo context's request trace and logger are passed along.

func TraceId

func TraceId(c echo.Context) string

TraceId returns the trace id for the request.

If it's already in the echo context, use that as this has already been called.

Otherwise, if it's provided in the request through one of the supported headers, set the response header trace id and cache in context. See SupportedTraceIdHeaders for where the trace id will be pulled from, in order of preference.

Otherwise, generate a new trace id, set the response header trace id and cache it in context.

func WithCacheControl

func WithCacheControl(enabled bool, value string) echo.MiddlewareFunc

Types

type Config

type Config struct {
	// If not provided, create an echo.New.
	App                    *echo.Echo
	Logger                 *logrus.Entry
	LoggingMiddlwareConfig LoggingMiddlwareConfig
	// Origins for echo's CORS middleware.
	// If it and CorsConfig are empty, do not add the middleware.
	CorsOrigins []string
	// Config for echo's CORS middleware.
	// Supercedes CorsOrigins.
	// If it and CorsOrigins are empty, do not add the middleware.
	CorsConfig *middleware.CORSConfig
	// Return this from the health endpoint.
	// Defaults to {"o":"k"}.
	HealthResponse map[string]interface{}
	// Defaults to /healthz.
	HealthPath string
	// If the health endpoint is not static
	// (for example so it can check whether a database is available),
	// provide this instead of HealthResponse.
	HealthHandler echo.HandlerFunc
	// Return this from the status endpoint.
	// The default is not very useful so you should provide a value.
	StatusResponse map[string]interface{}
	// Defaults to /statusz
	StatusPath string
	// If the status endpoint is not static,
	// provide this instead of StatusRespoinse.
	StatusHandler echo.HandlerFunc
}

type DebugMiddlewareConfig

type DebugMiddlewareConfig struct {
	Enabled             bool
	DumpRequestBody     bool
	DumpResponseBody    bool
	DumpRequestHeaders  bool
	DumpResponseHeaders bool
	DumpAll             bool
	// Log out memory stats every 'n' requests.
	// If <= 0, do not log them.
	DumpMemoryEvery int
}

type Error

type Error struct {
	HTTPStatus int
	ErrorCode  string
	Message    string
	Original   error
}

func NewError

func NewError(httpStatus int, errorCode string, original ...error) Error

func NewInternalError

func NewInternalError(original ...error) Error

func (Error) Error

func (e Error) Error() string

func (Error) MarshalJSON

func (e Error) MarshalJSON() ([]byte, error)

func (Error) ToMap

func (e Error) ToMap() map[string]interface{}

type LoggingMiddlwareConfig

type LoggingMiddlwareConfig struct {
	// If true, log request headers.
	RequestHeaders bool
	// If true, log response headers.
	ResponseHeaders bool
	// If provided, the returned logger is stored in the context
	// which is eventually passed to the handler.
	// Use to add additional fields to the logger based on the request.
	BeforeRequest func(echo.Context, *logrus.Entry) *logrus.Entry
	// If provided, the returned logger is used for response logging.
	// Use to add additional fields to the logger based on the request or response.
	AfterRequest func(echo.Context, *logrus.Entry) *logrus.Entry
	// The function that does the actual logging.
	// By default, it will log at a certain level based on the status code of the response.
	DoLog func(echo.Context, *logrus.Entry)
}

Directories

Path Synopsis
Package apiparams provides a framework-agnostic method for declarative parameter declaration and validation that should be used at the start of route handlers.
Package apiparams provides a framework-agnostic method for declarative parameter declaration and validation that should be used at the start of route handlers.
Package auth0jwt is a modification of the Auth0 provided Go tutorial: https://auth0.com/docs/quickstart/backend/golang As you may guess that has several issues, but a lot of what's here has been taken verbatim.
Package auth0jwt is a modification of the Auth0 provided Go tutorial: https://auth0.com/docs/quickstart/backend/golang As you may guess that has several issues, but a lot of what's here has been taken verbatim.
Package spa creates a set of middlewares for use when serving a Single Page Application from an API server.
Package spa creates a set of middlewares for use when serving a Single Page Application from an API server.

Jump to

Keyboard shortcuts

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