rest

package module
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2024 License: MIT Imports: 23 Imported by: 0

README

helix.go - REST router integration

Website Go API reference Go Report Card GitHub Release

The REST router integration provides an opinionated way to build a HTTP REST API with support for OpenAPI validations.

Documentation

Overview

Package rest exposes opinionated HTTP REST resources respecting the standards of the net/http package. In addition to a strong association with OpenTelemetry, it comes with OpenAPI support as well for request/response validation.

When using HTTP response writers, the calling function should return as soon as the handler function is called to avoid writing multiple times to the response writer.

Example:

MyHandlerFunc(rw http.ResponseWriter, req *http.Request) {
  if req.Header.Get("X-API-KEY") == "" {
    rest.Unauthorized(rw, req)
    return
  }
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddOrEditLanguage

func AddOrEditLanguage(lang language.Tag, locales map[int]string)

AddOrEditLanguage allows a service to add or edit a language support for error messages in the HTTP REST API, based on the status code returned.

Supported status code:

Example:

rest.AddOrEditLanguage(language.French, map[int]string{
	http.StatusBadRequest:            "<locale>",
	http.StatusUnauthorized:          "<locale>",
	http.StatusPaymentRequired:       "<locale>",
	http.StatusForbidden:             "<locale>",
	http.StatusNotFound:              "<locale>",
	http.StatusMethodNotAllowed:      "<locale>",
	http.StatusConflict:              "<locale>",
	http.StatusRequestEntityTooLarge: "<locale>",
	http.StatusTooManyRequests:       "<locale>",
	http.StatusInternalServerError:   "<locale>",
	http.StatusServiceUnavailable:    "<locale>",
})

func ParamsFromContext

func ParamsFromContext(ctx context.Context) (map[string]string, bool)

ParamsFromContext returns request's params found in the context passed, if any. Returns true if some params are present, false otherwise.

func WriteAccepted

func WriteAccepted(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteAccepted writes a 202 status code and body to the HTTP response writer.

WithErrorMessage and WithValidations have no effect here since no error is returned in 2xx responses.

func WriteBadRequest

func WriteBadRequest(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteBadRequest writes a 400 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 4xx responses.

Default error message (in English) is:

Failed to validate request

func WriteConflict

func WriteConflict(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteConflict writes a 409 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 4xx responses.

Default error message (in English) is:

Failed to process target resource because of conflict

func WriteCreated

func WriteCreated(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteCreated writes a 201 status code and body to the HTTP response writer.

WithErrorMessage and WithValidations have no effect here since no error is returned in 2xx responses.

func WriteForbidden

func WriteForbidden(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteForbidden writes a 403 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 4xx responses.

Default error message (in English) is:

You don't have required permissions to perform this action

func WriteInternalServerError

func WriteInternalServerError(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteInternalServerError writes a 500 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 5xx responses.

Default error message (in English) is:

We have been notified of this unexpected internal error

func WriteMethodNotAllowed

func WriteMethodNotAllowed(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteMethodNotAllowed writes a 405 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 4xx responses.

Default error message (in English) is:

Resource does not support this method

func WriteNotFound

func WriteNotFound(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteNotFound writes a 404 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 4xx responses.

Default error message (in English) is:

Resource does not exist

func WriteOK

func WriteOK(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteOK writes a 200 status code and body to the HTTP response writer.

WithErrorMessage and WithValidations have no effect here since no error is returned in 2xx responses.

func WritePaymentRequired

func WritePaymentRequired(rw http.ResponseWriter, req *http.Request, opts ...With)

WritePaymentRequired writes a 402 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 4xx responses.

Default error message (in English) is:

Request failed because payment is required

func WriteRequestEntityTooLarge

func WriteRequestEntityTooLarge(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteRequestEntityTooLarge writes a 413 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 4xx responses.

Default error message (in English) is:

Can not process payload too large

func WriteServiceUnavailable

func WriteServiceUnavailable(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteServiceUnavailable writes a 503 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 5xx responses.

Default error message (in English) is:

Please try again in a few moments

func WriteTooManyRequests

func WriteTooManyRequests(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteTooManyRequests writes a 429 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 4xx responses.

Default error message (in English) is:

Request-rate limit has been reached

func WriteUnauthorized

func WriteUnauthorized(rw http.ResponseWriter, req *http.Request, opts ...With)

WriteUnauthorized writes a 401 status code and body to the HTTP response writer.

WithData has no effect here since no data must be returned in 4xx responses.

Default error message (in English) is:

You are not authorized to perform this action

Types

type Config

type Config struct {

	// Address is the HTTP address to listen on.
	//
	// Default:
	//
	//   ":8080"
	Address string `json:"address"`

	// Middleware allows to wrap the built-in HTTP handler with a custom one, for
	// adding a chain of middlewares.
	Middleware func(next http.Handler) http.Handler `json:"-"`

	// Healthcheck allows to define custom logic for the healthcheck endpoint at:
	//
	//   GET /health
	//
	// It should return 200 if service is healthy, or 5xx if an error occurred.
	// Returns 200 by default.
	Healthcheck func(req *http.Request) int `json:"-"`

	// OpenAPI configures OpenAPI behavior within the REST API.
	OpenAPI ConfigOpenAPI `json:"openapi"`

	// TLSConfig configures TLS for the HTTP server. Only CertFile and KeyFile
	// are took into consideration. Filenames containing a certificate and matching
	// private key for the server must be provided. If the certificate is signed
	// by a certificate authority, the CertFile should be the concatenation of the
	// server's certificate, any intermediates, and the CA's certificate.
	TLS integration.ConfigTLS `json:"tls"`
}

Config is used to configure the HTTP REST integration.

type ConfigOpenAPI

type ConfigOpenAPI struct {

	// Enabled enables OpenAPI within the REST API.
	Enabled bool `json:"enabled"`

	// Description is a path to a local file or a URL containing the OpenAPI
	// description.
	//
	// Examples:
	//
	//   "./descriptions/openapi.yaml"
	//   "http://domain.tld/openapi.yaml"
	Description string `json:"description,omitempty"`
}

ConfigOpenAPI configures OpenAPI behavior within the REST API. When enabled, HTTP requests and responses are automatically validated againt the description passed. If a request is not valid, a 4xx error is returned to the client. If a response is not valid, an error is logged but the response is still returned to the client.

type REST

type REST interface {
	GET(path string, handler http.HandlerFunc)
	HEAD(path string, handler http.HandlerFunc)
	DELETE(path string, handler http.HandlerFunc)
	OPTIONS(path string, handler http.HandlerFunc)
	PATCH(path string, handler http.HandlerFunc)
	POST(path string, handler http.HandlerFunc)
	PUT(path string, handler http.HandlerFunc)
}

REST exposes the HTTP REST API functions.

func New

func New(cfg Config) (REST, error)

New tries to build a new HTTP API server for Config. Returns an error if Config or OpenAPI description are not valid.

type Response

type Response struct {

	// Status is the official text of the HTTP status code, in English.
	//
	// Example:
	//
	//   "Accepted"
	Status string `json:"status"`

	// Error represents a stack of errors and error validations. Error will always
	// be nil when returning a 2xx status using a response writer of this package.
	Error *errorstack.Error `json:"error,omitempty"`

	// Metadata represents metadata associated to the request/response.
	Metadata any `json:"metadata,omitempty"`

	// Data represents the data returned in the response. Data will always be nil
	// when returning a 4xx or 5xx status using a response writer of this package.
	Data any `json:"data,omitempty"`
}

Response is the JSON object every HTTP responses shall return.

type With

type With func(res *Response)

With allows to set optional values when calling some HTTP handler functions.

func WithData

func WithData(data any) With

WithData set the data object for the response.

WithData has no effect on non-2xx HTTP responses.

func WithErrorMessage

func WithErrorMessage(msg string) With

WithErrorMessage overrides the default translated error message. The translation of the default error message relies on the HTTP cookie or "Accept-Language" header. Using WithErrorMessage means it's up to the calling client to handle translation of the error message on its side (if desired).

WithErrorMessage has no effect on 2xx HTTP responses.

func WithMetadata

func WithMetadata(metadata any) With

WithMetadata set the metadata object for the response.

func WithValidations

func WithValidations(validations []errorstack.Validation) With

WithValidations adds validation errors to the main error.

WithValidations has no effect on 2xx HTTP responses.

Jump to

Keyboard shortcuts

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