server

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package server builds echo v4 HTTP servers with a consistent JSON response envelope and production-ready defaults.

NewHandler returns a builder that produces an *echo.Echo with:

  • a trace id per request (X-Trace-Id header, generated if missing), available via TraceIDFromContext;
  • CORS, panic recovery and an access log (zerolog) with masking of sensitive values (password, token, ...) in bodies and query strings;
  • a request body limit (10 MiB by default, 413 above it);
  • an error handler that renders every error, including echo's own 404/405, in the FailureResponse envelope with a status derived from sentinel errors such as ErrNotFound or ErrConflict.

Handlers answer with Ok, Created, Success, NoContent or Failure:

e := server.NewHandler(logger).Build()
e.GET("/users/:id", func(ctx echo.Context) error {
	user, err := repo.Get(ctx.Request().Context(), ctx.Param("id"))
	if err != nil {
		return err // e.g. fmt.Errorf("%w: user", server.ErrNotFound) -> 404
	}
	return server.Ok(ctx, user)
})

Request helpers (Parse, File, ParseForm), pagination helpers (PageParams, CursorPage, OffsetPage), a cookie builder (NewCookie) and a response cache middleware (CacheMiddleware) complete the package.

Index

Examples

Constants

View Source
const (
	// ResponseStatusCodeKey holds the status code written by [Success] or [Failure].
	ResponseStatusCodeKey = "api:response:status_code"
	// ResponseErrorKey holds the error passed to [Failure]; the access log reads it.
	ResponseErrorKey = "api:response:error"
	// ValidatorKey holds the *validator.Validate set by [ValidateMiddleware].
	ValidatorKey = "api:validator"
	// HideErrorDetailsKey is the echo context flag set by [HideErrorDetailsMiddleware].
	HideErrorDetailsKey = "api:hide-error-details"
)

Keys of values stored in the echo context by this package.

View Source
const (
	// TraceHeaderName is the request/response header carrying the trace id.
	TraceHeaderName = "X-Trace-Id"
	// TraceKey is the log field name and the legacy string context key of the trace id.
	TraceKey = "trace_id"
	// HandlerTraceKey is the echo context key of the trace id.
	HandlerTraceKey = "api:trace-id"
	// RawKey is the echo context flag set by [RawMiddleware].
	RawKey = "api:raw"
	// ResponseStoreKey is the echo context flag asking [Success] to keep the
	// response body in the context (under ResponseKey). Set it to false on a
	// route group to keep large bodies out of the access log.
	ResponseStoreKey = "api:store-response"
	// ResponseStatusStoreKey is the echo context flag asking [Success] to keep
	// the status code in the context (under ResponseStatusKey).
	ResponseStatusStoreKey = "api:store-response-status"
	// ResponseKey holds the response body stored by [Success].
	ResponseKey = "api:response"
	// ResponseStatusKey holds the status code stored by [Success].
	ResponseStatusKey = "api:response-status"
)

Header names and context keys used by the middlewares.

View Source
const (
	// DefaultPageSize is the page size used when the request has no page-size.
	DefaultPageSize = 20
	// DefaultMaxPageSize is the default upper bound of the page size.
	DefaultMaxPageSize = 1000
)
View Source
const DefaultBodyLimit int64 = 10 << 20

DefaultBodyLimit is the default limit of a request body size handled by HandlerBuilder: 10 MiB.

Services accepting bigger uploads (files, imports, attachments) raise it with HandlerBuilder.WithBodyLimit.

View Source
const (
	// DefaultLogBodyBytes is the default size of the request (and response) body prefix written to the log.
	DefaultLogBodyBytes = 128
)

Variables

View Source
var (
	// ErrHandlerReadFormFile is returned by [File] when the form file is missing or unreadable.
	ErrHandlerReadFormFile = errors.New("api.handler.read_form_file")
	// ErrHandlerOpenFormFile is returned by [File] when the uploaded file cannot be opened.
	ErrHandlerOpenFormFile = errors.New("api.handler.open_form_file")
	// ErrHandlerParseRequestBody is returned by [Parse] when binding the request fails.
	ErrHandlerParseRequestBody = errors.New("api.handler.parse_request_body")
	// ErrHandlerValidateRequestBody is returned by [Parse] when validation fails.
	ErrHandlerValidateRequestBody = errors.New("api.handler.validate_request_body")

	// ErrRouterRouteNotFound is answered (404) for requests to unknown routes.
	ErrRouterRouteNotFound = errors.New("api.router.route_not_found")
)

Errors returned by the request helpers of this package. They are sentinels: match them with errors.Is.

View Source
var (
	ErrBadRequest                  = errors.New("bad_request")
	ErrUnauthorized                = errors.New("unauthorized")
	ErrPaymentRequired             = errors.New("payment_required")
	ErrForbidden                   = errors.New("forbidden")
	ErrNotFound                    = errors.New("not_found")
	ErrMethodNotAllowed            = errors.New("method_not_allowed")
	ErrNotAcceptable               = errors.New("not_acceptable")
	ErrProxyAuthRequired           = errors.New("proxy_auth_required")
	ErrTimeout                     = errors.New("timeout")
	ErrConflict                    = errors.New("conflict")
	ErrGone                        = errors.New("gone")
	ErrLengthRequired              = errors.New("length_required")
	ErrPreconditionFailed          = errors.New("precondition_failed")
	ErrEntityTooLarge              = errors.New("entity_too_large")
	ErrURITooLong                  = errors.New("uri_too_long")
	ErrUnsupportedMediaType        = errors.New("unsupported_media_type")
	ErrRangeNotSatisfiable         = errors.New("range_not_satisfiable")
	ErrExpectationFailed           = errors.New("expectation_failed")
	ErrTeapot                      = errors.New("teapot")
	ErrMisdirectedRequest          = errors.New("misdirected_request")
	ErrUnprocessableEntity         = errors.New("unprocessable_entity")
	ErrLocked                      = errors.New("locked")
	ErrFailedDependency            = errors.New("failed_dependency")
	ErrTooEarly                    = errors.New("too_early")
	ErrUpgradeRequired             = errors.New("upgrade_required")
	ErrPreconditionRequired        = errors.New("precondition_required")
	ErrTooManyRequests             = errors.New("too_many_requests")
	ErrRequestHeaderFieldsTooLarge = errors.New("request_header_fields_too_large")
	ErrUnavailableForLegalReasons  = errors.New("unavailable_for_legal_reasons")

	ErrInternal                      = errors.New("internal")
	ErrNotImplemented                = errors.New("not_implemented")
	ErrBadGateway                    = errors.New("bad_gateway")
	ErrServiceUnavailable            = errors.New("service_unavailable")
	ErrGatewayTimeout                = errors.New("gateway_timeout")
	ErrHTTPVersionNotSupported       = errors.New("http_version_not_supported")
	ErrVariantAlsoNegotiates         = errors.New("variant_also_negotiates")
	ErrInsufficientStorage           = errors.New("insufficient_storage")
	ErrLoopDetected                  = errors.New("loop_detected")
	ErrNotExtended                   = errors.New("not_extended")
	ErrNetworkAuthenticationRequired = errors.New("network_authentication_required")
)

Status sentinels. Each one maps to exactly one HTTP status code in both directions: a handler returning an error that wraps (errors.Is) one of them is answered with that status by the error handler of HandlerBuilder, and Failure puts the sentinel of the chosen status into the "code" field of the envelope. An error matching none of them becomes 500 / ErrInternal.

Functions

func AfterLogMiddleware

func AfterLogMiddleware(logger zerolog.Logger) echo.MiddlewareFunc

AfterLogMiddleware logs the result of the request: method, url, status, trace id and error. The response body is not logged (see AfterLogMiddlewareWithConfig).

func AfterLogMiddlewareWithConfig

func AfterLogMiddlewareWithConfig(logger zerolog.Logger, cfg LogConfig) echo.MiddlewareFunc

AfterLogMiddlewareWithConfig is AfterLogMiddleware with the given LogConfig.

An error returned by the handler is passed to the error handler of echo (so the client gets the Failure envelope) and then logged with the resulting status.

func BeforeLogMiddleware

func BeforeLogMiddleware(logger zerolog.Logger) echo.MiddlewareFunc

BeforeLogMiddleware logs the request: method, url and a masked prefix of the body (see BeforeLogMiddlewareWithConfig; defaults: 128 bytes, default mask keys).

func BeforeLogMiddlewareWithConfig

func BeforeLogMiddlewareWithConfig(logger zerolog.Logger, cfg LogConfig) echo.MiddlewareFunc

BeforeLogMiddlewareWithConfig is BeforeLogMiddleware with the given LogConfig.

Only the prefix needed for the log is read from the request body, the handler still gets the whole body.

func CacheMiddleware

func CacheMiddleware(distributor CacheDistributor, ttl time.Duration) echo.MiddlewareFunc

CacheMiddleware serves responses from distributor and stores successful (2xx) responses of the handler in it for ttl.

A failing distributor never fails the request: an error of Get runs the handler as without the cache, an error of Set is ignored. The cache entry is stored before the response is sent, so the client always gets exactly one response.

func CookiesMap

func CookiesMap(ctx echo.Context) map[string]string

CookiesMap returns the request cookies as a name -> value map.

func Created

func Created(ctx echo.Context, body any) error

Created is wrap function over Success function.

Sets HTTP code "Created" 201

func Failure

func Failure(ctx echo.Context, statusCode int, err error) error

Failure returns response with some error status and convert provided error to errorOutput object and then convert it to JSON response.

Sets trace id to the response if it was in request context.

The "code" field is the sentinel of statusCode (see ErrBadRequest and friends); "message" is the error with exactly one level unwrapped (or only the top sentinel if error details are hidden, see HandlerBuilder.WithHiddenErrorDetails); validation errors of Parse are rendered as "params". A request body over the limit (*http.MaxBytesError) is always answered with 413.

Example
package main

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/labstack/echo/v4"
	"github.com/rs/zerolog"

	"github.com/boostgo/httpkit/server"
)

func main() {
	e := server.NewHandler(zerolog.Nop()).WithHiddenErrorDetails().Build()
	e.GET("/x", func(ctx echo.Context) error {
		return server.Failure(ctx, http.StatusInternalServerError, errors.New("pq: relation \"users\" does not exist"))
	})

	req := httptest.NewRequest(http.MethodGet, "/x", nil)
	req.Header.Set(server.TraceHeaderName, "trace-1")

	rec := httptest.NewRecorder()
	e.ServeHTTP(rec, req)

	fmt.Println(rec.Body.String())
}
Output:
{"status":"Failure","status_code":500,"message":"internal","code":"internal","request_id":"trace-1"}

func File

func File(ctx echo.Context, name string) ([]byte, error)

File reads the whole multipart form file with the given field name. Errors wrap ErrHandlerReadFormFile or ErrHandlerOpenFormFile.

func HeadersMap

func HeadersMap(ctx echo.Context) map[string]string

HeadersMap returns the request headers as a map; multiple values of one header are joined with ",".

func HideErrorDetailsMiddleware

func HideErrorDetailsMiddleware() echo.MiddlewareFunc

HideErrorDetailsMiddleware makes Failure answer with the top sentinel error only in "message" (see HandlerBuilder.WithHiddenErrorDetails). The full error stays in the context (ResponseErrorKey) and in the access log. Use it on a route group.

func MaxPages

func MaxPages(total int64, size int) int64

MaxPages returns the number of pages for total items and the page size.

func NoContent

func NoContent(ctx echo.Context) error

NoContent is a wrapper over Success with status "No Content" 204 and an empty body.

func Ok

func Ok(ctx echo.Context, body any) error

Ok is wrap function over Success function.

Sets HTTP code "OK" 200

func Parse

func Parse(ctx echo.Context, export any) error

Parse binds the request (path params, query, headers and body, see echo.Context.Bind) into export and, if a validator was installed with ValidateMiddleware, validates it.

Errors wrap ErrHandlerParseRequestBody or ErrHandlerValidateRequestBody; validation errors are rendered as "params" by Failure. A canceled request context is returned as is.

Example

ExampleParse binds and validates a JSON body; validation errors are rendered as "params" of the Failure envelope.

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/go-playground/validator/v10"
	"github.com/labstack/echo/v4"
	"github.com/rs/zerolog"

	"github.com/boostgo/httpkit/server"
)

func main() {
	type createUser struct {
		Name  string `json:"name" validate:"required,min=3"`
		Email string `json:"email" validate:"required,email"`
	}

	e := server.NewHandler(zerolog.Nop()).Build()
	e.Use(server.ValidateMiddleware(validator.New()))
	e.POST("/users", func(ctx echo.Context) error {
		var body createUser
		if err := server.Parse(ctx, &body); err != nil {
			return server.Failure(ctx, http.StatusBadRequest, err)
		}

		return server.Created(ctx, server.NewCreatedResponse(1))
	})

	req := httptest.NewRequest(http.MethodPost, "/users", strings.NewReader(`{"name":"al","email":"al@example.com"}`))
	req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
	req.Header.Set(server.TraceHeaderName, "trace-1")

	rec := httptest.NewRecorder()
	e.ServeHTTP(rec, req)

	var resp server.FailureResponse
	_ = json.Unmarshal(rec.Body.Bytes(), &resp)
	fmt.Println(resp.StatusCode, resp.Code, resp.Params[0].Key, resp.Params[0].Value, resp.Params[0].Expected)
}
Output:
400 bad_request Name min 3

func ParseForm

func ParseForm(ctx echo.Context) (map[string]string, error)

ParseForm parses a multipart form and returns the first value of every field. Files are ignored, use File for them.

func RawMiddleware

func RawMiddleware() echo.MiddlewareFunc

RawMiddleware makes Success write the body as plain JSON, without the SuccessResponse envelope. Use it on routes consumed by third parties.

func RecoverMiddleware

func RecoverMiddleware(config middleware.RecoverConfig) echo.MiddlewareFunc

RecoverMiddleware returns a middleware which recovers from panics anywhere in the chain and handles the control to the centralized HTTPErrorHandler.

If the response is already started when the panic happens, the panic is only logged (see config.LogErrorFunc): a second body would corrupt the response.

func ReturnExcel

func ReturnExcel(ctx echo.Context, name string, file []byte) error

ReturnExcel returns response with Excel file content type

func SetContext

func SetContext(handlerCtx echo.Context, ctx context.Context) error

SetContext replaces the context of the request with ctx. It fails with the context error if either ctx or the current request context is already done.

func Success

func Success(ctx echo.Context, statusCode int, body any) error

Success returns response with success code & successOutput object and convert it to JSON response.

Sets trace id to the response if it was in request context.

If provided body exist, and it is "primitive" response will be in raw (no successOutput object).

If context contain "raw" middleware key, response will be in raw (no successOutput object).

If body is not provided, will be returned empty string

func TraceIDFromContext

func TraceIDFromContext(ctx context.Context) string

TraceIDFromContext returns the trace id put into the request context by TraceMiddleware. It returns an empty string if there is none.

func TraceMiddleware

func TraceMiddleware() echo.MiddlewareFunc

TraceMiddleware takes the trace id from the TraceHeaderName header (or generates one) and stores it in the echo context (HandlerTraceKey, TraceKey) and in the request context (see TraceIDFromContext; the string key TraceKey is still written for the services reading it).

func UnknownError

func UnknownError(ctx echo.Context, err error) error

UnknownError answers with 500 and an error wrapping ErrInternal.

func ValidateMiddleware

func ValidateMiddleware(validate *validator.Validate) echo.MiddlewareFunc

ValidateMiddleware installs validate into the echo context, so Parse validates the bound structs with it.

Types

type CacheDistributor

type CacheDistributor interface {
	// Get returns the cached response body for the request. found reports
	// whether an entry exists. A non-nil error makes the middleware run the
	// handler as if there was no cache.
	Get(ctx context.Context, request *http.Request) (body []byte, found bool, err error)
	// Set stores the response body of the request for ttl. Its error is
	// ignored by the middleware.
	Set(ctx context.Context, request *http.Request, responseBody []byte, ttl time.Duration) error
}

CacheDistributor is a response cache backend used by CacheMiddleware.

Implementations decide how a request maps to a cache key (for example method + URL + selected headers) and where the bytes are stored (memory, Redis, ...).

type Config

type Config struct {
	Addr              string     `json:"addr" yaml:"addr"`
	ReadTimeout       TimeConfig `json:"read_timeout" yaml:"readTimeout"`
	ReadHeaderTimeout TimeConfig `json:"read_header_timeout" yaml:"readHeaderTimeout"`
	WriteTimeout      TimeConfig `json:"write_timeout" yaml:"writeTimeout"`
	IdleTimeout       TimeConfig `json:"idle_timeout" yaml:"idleTimeout"`
	MaxHeaderBytes    int        `json:"max_header_bytes" yaml:"maxHeaderBytes"`
}

Config holds the settings of an net/http.Server in a form convenient for JSON/YAML configuration files. The package does not start servers itself; copy the values into your http.Server:

srv := &http.Server{
	Addr:              cfg.Addr,
	Handler:           e,
	ReadTimeout:       cfg.ReadTimeout.Duration(),
	ReadHeaderTimeout: cfg.ReadHeaderTimeout.Duration(),
	WriteTimeout:      cfg.WriteTimeout.Duration(),
	IdleTimeout:       cfg.IdleTimeout.Duration(),
	MaxHeaderBytes:    cfg.MaxHeaderBytes,
}

type CookieBuilder

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

CookieBuilder builds an http.Cookie with a fluent API:

ctx.SetCookie(server.NewCookie("session", id).
	WithHttpOnly(true).
	WithSecure(true).
	WithSameSite(http.SameSiteLaxMode).
	WithMaxAage(3600).
	Build())

func NewCookie

func NewCookie(name, value string) *CookieBuilder

NewCookie starts a cookie with the given name and value. Path defaults to "/".

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/boostgo/httpkit/server"
)

func main() {
	cookie := server.NewCookie("session", "abc").
		WithHttpOnly(true).
		WithSecure(true).
		WithSameSite(http.SameSiteLaxMode).
		WithMaxAage(3600).
		Build()

	fmt.Println(cookie.String())
}
Output:
session=abc; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax

func (*CookieBuilder) Build

func (c *CookieBuilder) Build() *http.Cookie

Build returns the cookie. No security flags are forced: set Secure, HttpOnly and SameSite explicitly.

func (*CookieBuilder) WithDomain

func (c *CookieBuilder) WithDomain(domain string) *CookieBuilder

WithDomain sets http.Cookie.Domain.

func (*CookieBuilder) WithExpiresAt

func (c *CookieBuilder) WithExpiresAt(expiresAt time.Time) *CookieBuilder

WithExpiresAt sets http.Cookie.Expires.

func (*CookieBuilder) WithHttpOnly

func (c *CookieBuilder) WithHttpOnly(httpOnly bool) *CookieBuilder

WithHttpOnly sets http.Cookie.HttpOnly.

func (*CookieBuilder) WithMaxAage

func (c *CookieBuilder) WithMaxAage(maxAge int) *CookieBuilder

WithMaxAage sets http.Cookie.MaxAge in seconds. The name keeps its historical spelling for compatibility.

func (*CookieBuilder) WithPartitioned

func (c *CookieBuilder) WithPartitioned(partitioned bool) *CookieBuilder

WithPartitioned sets http.Cookie.Partitioned.

func (*CookieBuilder) WithPath

func (c *CookieBuilder) WithPath(path string) *CookieBuilder

WithPath sets http.Cookie.Path.

func (*CookieBuilder) WithQuoted

func (c *CookieBuilder) WithQuoted(quoted bool) *CookieBuilder

WithQuoted sets http.Cookie.Quoted.

func (*CookieBuilder) WithRaw

func (c *CookieBuilder) WithRaw(raw string) *CookieBuilder

WithRaw sets http.Cookie.Raw.

func (*CookieBuilder) WithRawExpires

func (c *CookieBuilder) WithRawExpires(expires string) *CookieBuilder

WithRawExpires sets http.Cookie.RawExpires.

func (*CookieBuilder) WithSameSite

func (c *CookieBuilder) WithSameSite(sameSite http.SameSite) *CookieBuilder

WithSameSite sets http.Cookie.SameSite.

func (*CookieBuilder) WithSecure

func (c *CookieBuilder) WithSecure(secure bool) *CookieBuilder

WithSecure sets http.Cookie.Secure.

func (*CookieBuilder) WithUnparsed

func (c *CookieBuilder) WithUnparsed(unparsed []string) *CookieBuilder

WithUnparsed sets http.Cookie.Unparsed.

type CreatedResponse

type CreatedResponse struct {
	ID any `json:"id"`
}

CreatedResponse is a conventional body for "201 Created" answers.

func NewCreatedResponse

func NewCreatedResponse(id any) CreatedResponse

NewCreatedResponse builds a CreatedResponse with the given id.

type CursorPage

type CursorPage struct {
	NextCursor *string `json:"next_cursor"`
	HasMore    bool    `json:"has_more"`
}

CursorPage is the metadata of a cursor page, embedded into the service response next to the list of items:

type UsersResponse struct {
	Users []User `json:"users"`
	server.CursorPage
}

NextCursor is null at the end. There is no prev_cursor: a UI goes back with a stack of cursors.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/boostgo/httpkit/server"
)

func main() {
	type response struct {
		Items []string `json:"items"`
		server.CursorPage
	}

	raw, _ := json.Marshal(response{Items: []string{"a", "b"}})
	fmt.Println(string(raw))
}
Output:
{"items":["a","b"],"next_cursor":null,"has_more":false}

type FailureResponse

type FailureResponse struct {
	Status     string  `json:"status"`
	StatusCode int     `json:"status_code"`
	Message    string  `json:"message"`
	Code       string  `json:"code"`
	Inner      string  `json:"inner,omitempty"`
	Params     []Param `json:"params,omitempty"`
	RequestID  string  `json:"request_id,omitempty"`
}

FailureResponse is the JSON envelope written by Failure:

{"status":"Failure","status_code":404,"message":"...","code":"not_found","params":[...],"request_id":"..."}

Code is the status sentinel (see ErrNotFound and friends), Message is the error text (or only its top sentinel with hidden error details).

func NewFailureResponse

func NewFailureResponse(
	code, message error,
	statusCode int,
	requestID string,
	params ...Param,
) FailureResponse

NewFailureResponse builds a FailureResponse envelope.

type HandlerBuilder

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

HandlerBuilder builds an echo handler with the standard middlewares.

func NewHandler

func NewHandler(logger zerolog.Logger) *HandlerBuilder

NewHandler returns a builder with the standard middlewares: trace, CORS, recover, request and access log.

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/labstack/echo/v4"
	"github.com/rs/zerolog"

	"github.com/boostgo/httpkit/server"
)

func main() {
	e := server.NewHandler(zerolog.Nop()).
		WithBodyLimit(1<<20).
		WithBodyLog(64, "passport").
		WithCORSOrigins("https://app.example.com").
		WithHiddenErrorDetails().
		Build()

	e.GET("/hello", func(ctx echo.Context) error {
		return server.Ok(ctx, map[string]string{"hello": "world"})
	})

	req := httptest.NewRequest(http.MethodGet, "/hello", nil)
	req.Header.Set(server.TraceHeaderName, "trace-1")

	rec := httptest.NewRecorder()
	e.ServeHTTP(rec, req)

	fmt.Println(rec.Code, rec.Body.String())
}
Output:
200 {"status":"Success","status_code":200,"body":{"hello":"world"},"request_id":"trace-1"}
Example (SentinelErrors)

ExampleNewHandler_sentinelErrors shows how returned errors map to statuses.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/labstack/echo/v4"
	"github.com/rs/zerolog"

	"github.com/boostgo/httpkit/server"
)

func main() {
	e := server.NewHandler(zerolog.Nop()).Build()
	e.GET("/users/:id", func(ctx echo.Context) error {
		return fmt.Errorf("%w: user %s", server.ErrNotFound, ctx.Param("id"))
	})

	req := httptest.NewRequest(http.MethodGet, "/users/7", nil)
	req.Header.Set(server.TraceHeaderName, "trace-1")

	rec := httptest.NewRecorder()
	e.ServeHTTP(rec, req)

	fmt.Println(rec.Code, rec.Body.String())
}
Output:
404 {"status":"Failure","status_code":404,"message":"not_found","code":"not_found","request_id":"trace-1"}

func (*HandlerBuilder) Build

func (h *HandlerBuilder) Build() *echo.Echo

Build returns the echo handler.

func (*HandlerBuilder) WithBodyLimit

func (h *HandlerBuilder) WithBodyLimit(n int64) *HandlerBuilder

WithBodyLimit sets the limit of a request body size in bytes (DefaultBodyLimit by default). A bigger body is answered with 413 and the Failure envelope. n <= 0 means no limit.

func (*HandlerBuilder) WithBodyLog

func (h *HandlerBuilder) WithBodyLog(maxBytes int, maskKeys ...string) *HandlerBuilder

WithBodyLog sets the size of the request body prefix written to the log (128 by default, 0 turns the body log off) and extra keys whose values are masked. The keys "password", "client_secret", "token" and "msisdn" are always masked.

func (*HandlerBuilder) WithCORSOrigins

func (h *HandlerBuilder) WithCORSOrigins(origins ...string) *HandlerBuilder

WithCORSOrigins sets the allowed CORS origins. By default any origin ("*") is allowed.

func (*HandlerBuilder) WithHiddenErrorDetails

func (h *HandlerBuilder) WithHiddenErrorDetails() *HandlerBuilder

WithHiddenErrorDetails makes Failure show only the top sentinel error in "message" for the whole handler (internal texts of drivers stay in the access log). Off by default; for single groups use HideErrorDetailsMiddleware.

func (*HandlerBuilder) WithHideBanner

func (h *HandlerBuilder) WithHideBanner(hideBanner bool) *HandlerBuilder

WithHideBanner sets echo HideBanner.

func (*HandlerBuilder) WithHidePort

func (h *HandlerBuilder) WithHidePort(hidePort bool) *HandlerBuilder

WithHidePort sets echo HidePort.

func (*HandlerBuilder) WithMiddleware

func (h *HandlerBuilder) WithMiddleware(middleware echo.MiddlewareFunc) *HandlerBuilder

WithMiddleware adds a middleware after the current ones.

func (*HandlerBuilder) WithMiddlewares

func (h *HandlerBuilder) WithMiddlewares(middlewares []echo.MiddlewareFunc) *HandlerBuilder

WithMiddlewares replaces the whole list of the default middlewares.

The body limit and the error handler do not depend on the list and still apply.

func (*HandlerBuilder) WithResponseBodyLog

func (h *HandlerBuilder) WithResponseBodyLog() *HandlerBuilder

WithResponseBodyLog turns on the response body prefix in the access log (same size and masking as for the request). It is off by default. A route group can turn it off with ctx.Set(ResponseStoreKey, false).

type LogConfig

type LogConfig struct {
	// BodyBytes is the size of the request body prefix written to the log.
	// Zero disables the request body log. Negative means [DefaultLogBodyBytes].
	BodyBytes int
	// MaskKeys are extra keys whose values are masked; "password", "client_secret", "token"
	// and "msisdn" are always masked.
	MaskKeys []string
	// ResponseBody turns on the response body prefix in the log (off by default, it costs
	// an extra copy of the response). A route group can still turn it off with
	// ctx.Set(ResponseStoreKey, false).
	ResponseBody bool
}

LogConfig configures the access-log middlewares.

type OffsetPage

type OffsetPage struct {
	CursorPage

	Page     int   `json:"page"`
	PageSize int   `json:"page_size"`
	Total    int64 `json:"total"`
	MaxPages int64 `json:"max_pages"`
}

OffsetPage is the metadata of an offset page (screens with page numbers). It also carries next_cursor and has_more.

Example

ExampleOffsetPage shows a list endpoint with offset pagination.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/labstack/echo/v4"
	"github.com/rs/zerolog"

	"github.com/boostgo/httpkit/server"
)

func main() {
	type user struct {
		ID   int    `json:"id"`
		Name string `json:"name"`
	}

	type usersResponse struct {
		Users []user `json:"users"`
		server.OffsetPage
	}

	all := []user{{1, "ann"}, {2, "bob"}, {3, "cid"}, {4, "dan"}, {5, "eve"}}

	e := server.NewHandler(zerolog.Nop()).Build()
	e.GET("/users", func(ctx echo.Context) error {
		var params server.PageParams
		if err := server.Parse(ctx, &params); err != nil {
			return server.Failure(ctx, http.StatusBadRequest, err)
		}

		page := params.Normalize(server.MaxPageSize(100))
		from := min((page.Page-1)*page.Size, len(all))
		to := min(from+page.Size, len(all))

		return server.Ok(ctx, usersResponse{
			Users: all[from:to],
			OffsetPage: server.OffsetPage{
				CursorPage: server.CursorPage{HasMore: to < len(all)},
				Page:       page.Page,
				PageSize:   page.Size,
				Total:      int64(len(all)),
				MaxPages:   server.MaxPages(int64(len(all)), page.Size),
			},
		})
	})

	req := httptest.NewRequest(http.MethodGet, "/users?page=2&page-size=2", nil)
	req.Header.Set(server.TraceHeaderName, "trace-1")

	rec := httptest.NewRecorder()
	e.ServeHTTP(rec, req)

	fmt.Println(rec.Body.String())
}
Output:
{"status":"Success","status_code":200,"body":{"users":[{"id":3,"name":"cid"},{"id":4,"name":"dan"}],"next_cursor":null,"has_more":true,"page":2,"page_size":2,"total":5,"max_pages":3},"request_id":"trace-1"}

type PageOption

type PageOption func(*pageOptions)

PageOption tunes PageParams.Normalize.

func MaxPageSize

func MaxPageSize(n int) PageOption

MaxPageSize sets the upper bound of the page size for an endpoint (DefaultMaxPageSize by default). n <= 0 keeps the default.

type PageParams

type PageParams struct {
	Page   int    `query:"page" form:"page" default:"1"`
	Size   int64  `query:"page-size" form:"page-size" default:"20"`
	Cursor string `query:"cursor" form:"cursor"`
}

PageParams are the pagination parameters of a request: offset (page, page-size) or cursor.

The `default` tags are not applied by echo: without the parameters the fields stay zero. The defaults are set by PageParams.Normalize, which is never called implicitly.

func (PageParams) Normalize

func (p PageParams) Normalize(opts ...PageOption) PageRequest

Normalize turns the raw parameters into a safe request: the size is 20 without page-size and is cut to the maximum (1000 by default) when too big, page <= 0 becomes 1. The result never means "the whole table": Size is always in [1, max].

The cursor is passed as is (an opaque token, validated by the pager). page and cursor given together are passed as is too.

Example
package main

import (
	"fmt"

	"github.com/boostgo/httpkit/server"
)

func main() {
	fmt.Println(server.PageParams{}.Normalize())
	fmt.Println(server.PageParams{Page: -1, Size: 10_000_000}.Normalize())
	fmt.Println(server.PageParams{Size: 10_000_000}.Normalize(server.MaxPageSize(5000)))
	fmt.Println(server.PageParams{Cursor: "abc", Size: 50}.Normalize())
}
Output:
{1 20 }
{1 1000 }
{1 5000 }
{1 50 abc}

type PageRequest

type PageRequest struct {
	Page   int
	Size   int
	Cursor string
}

PageRequest is the normalized pagination request returned by PageParams.Normalize.

It deliberately has only plain fields (Page, Size, Cursor in this order), so a repository layer can convert it to its own page request type with the same fields by a simple type conversion; this package does not depend on any database library.

type Param

type Param struct {
	// Key is the field name.
	Key string `json:"key"`
	// Value is the failed rule (validator tag).
	Value string `json:"value"`
	// Description is a human-readable explanation.
	Description string `json:"description"`
	// Expected is the rule parameter, if any (e.g. "3" for min=3).
	Expected string `json:"expected,omitempty"`
}

Param describes one problem with the request, for example a failed validation rule. It is rendered in the "params" array of FailureResponse.

type SortByParams

type SortByParams struct {
	Field string `json:"field" query:"sort-by-field" form:"sort-by-field"`
	Asc   bool   `json:"asc" query:"sort-by-asc" form:"sort-by-asc"`
}

SortByParams are the sorting parameters of a request (?sort-by-field=name&sort-by-asc=true).

type SuccessResponse

type SuccessResponse struct {
	Status     string `json:"status"`
	StatusCode int    `json:"status_code"`
	Body       any    `json:"body"`
	RequestID  string `json:"request_id,omitempty"`
}

SuccessResponse is the JSON envelope written by Success:

{"status":"Success","status_code":200,"body":{...},"request_id":"..."}

func NewSuccessResponse

func NewSuccessResponse(body any, statusCode int, requestID string) SuccessResponse

NewSuccessResponse builds a SuccessResponse envelope.

type SwaggerConfig

type SwaggerConfig struct {
	Host             string   `json:"host" yaml:"host"`
	Version          string   `json:"version" yaml:"version"`
	BasePath         string   `json:"base_path" yaml:"basePath"`
	Schemes          []string `json:"schemes" yaml:"schemes"`
	Title            string   `json:"title" yaml:"title"`
	Description      string   `json:"description" yaml:"description"`
	InfoInstanceName string   `json:"info_instance_name" yaml:"infoInstanceName"`
	SwaggerTemplate  string   `json:"swagger_template" yaml:"swaggerTemplate"`
	LeftDelim        string   `json:"left_delim" yaml:"leftDelim"`
	RightDelim       string   `json:"right_delim" yaml:"rightDelim"`
}

SwaggerConfig overrides fields of a generated swag specification (see github.com/swaggo/swag) from configuration. Empty fields are left as generated.

func (SwaggerConfig) Apply

func (s SwaggerConfig) Apply(cfg *swag.Spec)

Apply copies the non-empty fields of s into cfg, typically the generated docs.SwaggerInfo.

type TimeConfig

type TimeConfig struct {
	Milliseconds int64 `json:"milliseconds"`
	Seconds      int64 `json:"seconds"`
	Minutes      int64 `json:"minutes"`
	Hours        int   `json:"hours"`
}

TimeConfig is a duration split into units for configuration files. All units are summed up by TimeConfig.Duration.

func (TimeConfig) Duration

func (t TimeConfig) Duration() time.Duration

Duration returns the sum of all units as a time.Duration.

Jump to

Keyboard shortcuts

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