rest

package module
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2023 License: MIT Imports: 23 Imported by: 0

README

REST with Clean Architecture for Go

GoDevDoc

Inspired by swaggest/rest

Features

Usage

Request

Go struct with field tags defines input.

// Declare input port type.
type helloInput struct {
    Locale string `query:"locale" default:"en-US" pattern:"^[a-z]{2}-[A-Z]{2}$" enum:"zh-CN,en-US"`
    Name   string `path:"name" minLength:"3"` // Field tags define parameter location and JSON schema constraints.

    _      struct{} `title:"My Struct" description:"Holds my data."`
}

Input data can be located in:

  • path parameter in request URI, e.g. /users/:name,
  • query parameter in request URI, e.g. /users?locale=en-US,
  • form parameter in request body with application/x-www-form-urlencoded content,
  • formData parameter in request body with multipart/form-data content,
  • json parameter in request body with application/json content,
  • cookie parameter in request cookie,
  • header parameter in request header.

Field tags

  • number maximum, exclusiveMaximum, minimum, exclusiveMinimum, multipleOf
  • string minLength, maxLength, pattern, format
  • array minItems, maxItems, uniqueItems
  • all title, description, default, const, enum

Additional field tags describe JSON schema constraints, please check documentation.

Response

// Declare output port type.
type helloOutput struct {
    Now     time.Time `header:"X-Now" json:"-"`
    Message string    `json:"message"`
    Sess    string    `cookie:"sess,httponly,secure,max-age=86400,samesite=lax"`
}

Output data can be located in:

  • json for response body with application/json content,
  • header for values in response header,
  • cookie for cookie values, cookie fields can have configuration in field tag (same as in actual cookie, but with comma separation).

Example

Advance Example

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/fourcels/rest"
	"github.com/labstack/echo/v4"
)

func main() {
	s := rest.NewService()
	s.OpenAPI.Info.WithTitle("Basic Example")
	s.GET("/hello/{name}", hello())

	// Swagger UI endpoint at /docs.
	s.Docs("/docs")

	// Start server.
	log.Println("http://localhost:1323/docs")
	s.Start(":1323")
}

func hello() rest.Interactor {
	// Declare input port type.
	type input struct {
		Name   string   `path:"name" minLength:"3"` // Field tags define parameter
		Locale string   `query:"locale" default:"en-US" pattern:"^[a-z]{2}-[A-Z]{2}$" enum:"zh-CN,en-US"`
		_      struct{} `title:"My Struct" description:"Holds my data."`
	}

	// Declare output port type.
	type output struct {
		Now     time.Time `header:"X-Now" json:"-"`
		Message string    `json:"message"`
	}

	messages := map[string]string{
		"en-US": "Hello, %s!",
		"zh-CN": "你好, %s!",
	}
	return rest.NewHandler(func(c echo.Context, in input, out *output) error {
		msg := messages[in.Locale]
		out.Now = time.Now()
		out.Message = fmt.Sprintf(msg, in.Name)
		return nil
	})
}

Documentation

Index

Constants

View Source
const (
	// ParamInPath indicates path parameters, such as `/users/{id}`.
	ParamInPath = ParamIn("path")

	// ParamInQuery indicates query parameters, such as `/users?page=10`.
	ParamInQuery = ParamIn("query")

	// ParamInBody indicates body value, such as `{"id": 10}`.
	ParamInBody = ParamIn("json")

	// ParamInFormData indicates body form parameters.
	ParamInForm = ParamIn("form")

	// ParamInFormData indicates body form parameters.
	ParamInFormData = ParamIn("formData")

	// ParamInCookie indicates cookie parameters, which are passed ParamIn the `Cookie` header,
	// such as `Cookie: debug=0; gdpr=2`.
	ParamInCookie = ParamIn("cookie")

	// ParamInHeader indicates header parameters, such as `X-Header: value`.
	ParamInHeader = ParamIn("header")
)
View Source
const (
	SchemeBearer = Scheme("bearer")
	SchemeBasic  = Scheme("basic")
)

Variables

This section is empty.

Functions

func WithDescription added in v0.2.2

func WithDescription(val string) option

func WithSecurity added in v0.2.2

func WithSecurity(key string) option

func WithSummary added in v0.2.2

func WithSummary(val string) option

func WithTags added in v0.2.2

func WithTags(val ...string) option

Types

type CustomBinder

type CustomBinder struct{}

func (*CustomBinder) Bind

func (b *CustomBinder) Bind(i interface{}, c echo.Context) (err error)

Bind implements the `Binder#Bind` function. Binding is done in following order: 1) path params; 2) query params; 3) request body. Each step COULD override previous step binded values. For single source binding use their own methods BindBody, BindQueryParams, BindPathParams.

func (*CustomBinder) BindBody

func (b *CustomBinder) BindBody(c echo.Context, i interface{}) (err error)

BindBody binds request body contents to bindable object NB: then binding forms take note that this implementation uses standard library form parsing which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm See non-MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseForm See MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseMultipartForm

func (*CustomBinder) BindCookies

func (b *CustomBinder) BindCookies(c echo.Context, i interface{}) error

func (*CustomBinder) BindHeaders added in v0.2.5

func (b *CustomBinder) BindHeaders(c echo.Context, i interface{}) error

BindHeaders binds HTTP headers to a bindable object

func (*CustomBinder) BindPathParams

func (b *CustomBinder) BindPathParams(c echo.Context, i interface{}) error

BindPathParams binds path params to bindable object

func (*CustomBinder) BindQueryParams added in v0.2.5

func (b *CustomBinder) BindQueryParams(c echo.Context, i interface{}) error

BindQueryParams binds query params to bindable object

type CustomValidator

type CustomValidator struct{}

func (*CustomValidator) Validate

func (cv *CustomValidator) Validate(i any) error

type ErrResponse

type ErrResponse struct {
	StatusText string                 `json:"status,omitempty" description:"Status text."`
	AppCode    int                    `json:"code,omitempty" description:"Application-specific error code."`
	ErrorText  string                 `json:"error,omitempty" description:"Error message."`
	Context    map[string]interface{} `json:"context,omitempty" description:"Application context."`
	// contains filtered or unexported fields
}

ErrResponse is HTTP error response body.

func Err

func Err(err error) (int, ErrResponse)

func (ErrResponse) Error

func (e ErrResponse) Error() string

Error implements error.

func (ErrResponse) Unwrap

func (e ErrResponse) Unwrap() error

Unwrap returns parent error.

type ErrWithAppCode

type ErrWithAppCode interface {
	error
	AppErrCode() int
}

ErrWithAppCode exposes application error code.

type ErrWithFields

type ErrWithFields interface {
	error
	Fields() map[string]interface{}
}

ErrWithFields exposes structured context of error.

type ErrWithHTTPStatus

type ErrWithHTTPStatus interface {
	error
	HTTPStatus() int
}

ErrWithHTTPStatus exposes HTTP status code.

type Group added in v0.2.0

type Group struct {
	*echo.Group
	// contains filtered or unexported fields
}

func (*Group) DELETE added in v0.2.0

func (g *Group) DELETE(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

func (*Group) GET added in v0.2.0

func (g *Group) GET(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

func (*Group) PATCH added in v0.2.0

func (g *Group) PATCH(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

func (*Group) POST added in v0.2.0

func (g *Group) POST(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

func (*Group) PUT added in v0.2.0

func (g *Group) PUT(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

type HTTPCodeAsError

type HTTPCodeAsError int

HTTPCodeAsError exposes HTTP status code as use case error that can be translated to response status.

func (HTTPCodeAsError) Error

func (c HTTPCodeAsError) Error() string

Error return HTTP status text.

func (HTTPCodeAsError) HTTPStatus

func (c HTTPCodeAsError) HTTPStatus() int

HTTPStatus returns HTTP status code.

type Handler

type Handler[i, o any] struct {
	// contains filtered or unexported fields
}

func (*Handler[i, o]) Input

func (h *Handler[i, o]) Input() any

func (*Handler[i, o]) Interact

func (h *Handler[i, o]) Interact(c echo.Context, in, out any) error

func (*Handler[i, o]) Options

func (h *Handler[i, o]) Options() []option

func (*Handler[i, o]) Output

func (h *Handler[i, o]) Output() any

func (*Handler[i, o]) Summary added in v0.2.4

func (h *Handler[i, o]) Summary() string

type Interactor

type Interactor interface {
	Input() any
	Output() any
	Interact(c echo.Context, in, out any) error
	Options() []option
	Summary() string
}

func NewHandler

func NewHandler[i, o any](handler interact[i, o], ops ...option) Interactor

type NoContent added in v0.4.4

type NoContent struct{}

type ParamIn

type ParamIn string

ParamIn defines parameter location.

type Scheme

type Scheme string

type Service

type Service struct {
	*echo.Echo

	OpenAPI *openapi3.Spec
	// contains filtered or unexported fields
}

func NewService added in v0.2.2

func NewService(baseUrl ...string) *Service

func (*Service) DELETE

func (s *Service) DELETE(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

func (*Service) Docs

func (s *Service) Docs(pattern string, config ...map[string]any)

func (*Service) GET

func (s *Service) GET(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

func (*Service) Group

func (s *Service) Group(prefix string, ops ...option) *Group

func (*Service) PATCH

func (s *Service) PATCH(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

func (*Service) POST

func (s *Service) POST(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

func (*Service) PUT

func (s *Service) PUT(pattern string, h Interactor, middleware ...echo.MiddlewareFunc) *echo.Route

func (*Service) WithAPIKeySecurity

func (s *Service) WithAPIKeySecurity(key, name string, in openapi3.APIKeySecuritySchemeIn)

func (*Service) WithHttpBasicSecurity added in v0.2.2

func (s *Service) WithHttpBasicSecurity(key string)

func (*Service) WithHttpBearerSecurity added in v0.2.2

func (s *Service) WithHttpBearerSecurity(key string)

func (*Service) WithHttpSecurity

func (s *Service) WithHttpSecurity(key string, scheme Scheme)

func (*Service) WithSecurity

func (s *Service) WithSecurity(key string, securityScheme *openapi3.SecurityScheme)

func (*Service) WithTags added in v0.5.5

func (s *Service) WithTags(val ...string)

type ValidatorError

type ValidatorError struct {
	HTTPCodeAsError

	ValidationError *gojsonschema.ValidationError
	// contains filtered or unexported fields
}

func (*ValidatorError) Error added in v0.2.1

func (*ValidatorError) Error() string

func (*ValidatorError) Fields

func (ve *ValidatorError) Fields() map[string]any

Jump to

Keyboard shortcuts

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