optizz

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2021 License: MIT Imports: 16 Imported by: 0

README

Optizz

Optizz := Tonic + wI2L/Fizz

  • Tonic handle style for Fiber
  • wI2L/Fizz OpenAPI generator

The original code are from Tonic and wI2L/Fizz and then modified to work with Fiber.

Example

app := fiber.New()

z := optizz.NewFromApp(app)

api := z.Group("api", "api", "API routes")
{
    api.Post("ping/:path1", optizz.Handler(pingPongHandler, 200,
        optizz.Summary("this is a summary"),
        optizz.Description("ping pong"),
    ))
}

app.Get("openapi.json", z.OpenAPI(&openapi.Info{
    Title:       "example",
    Description: "example",
    Version:     "1.0.0",
}, "json"))

OpenAPI

curl localhost:8080/openapi.json

{
  "openapi": "3.0.1",
  "info": {
    "title": "example",
    "description": "example",
    "version": "1.0.0"
  },
  "paths": {
    "api/ping/{path1}": {
      "post": {
        "tags": [
          "api"
        ],
        "summary": "this is a summary",
        "description": "ping pong",
        "operationId": "pingPongHandler",
        "parameters": [
          {
            "name": "path1",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "query1",
            "in": "query",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "X-Header-1",
            "in": "header",
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PingPongHandlerInput"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Output"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "Output": {
        "type": "object",
        "properties": {
          "X-Header-1": {
            "type": "string"
          },
          "body_nested": {
            "type": "object",
            "additionalProperties": {}
          },
          "body_number": {
            "type": "string"
          },
          "body_string": {
            "type": "string"
          },
          "path1": {
            "type": "string"
          },
          "query1": {
            "type": "string"
          }
        }
      },
      "PingPongHandlerInput": {
        "type": "object",
        "properties": {
          "body_nested": {
            "type": "object",
            "additionalProperties": {}
          },
          "body_number": {
            "type": "string"
          },
          "body_string": {
            "type": "string"
          }
        },
        "required": [
          "body_string"
        ]
      }
    }
  },
  "tags": [
    {
      "name": "api",
      "description": "API routes"
    }
  ]
}

Documentation

Index

Constants

View Source
const (
	QueryTag      = "query"
	PathTag       = "path"
	HeaderTag     = "header"
	EnumTag       = "enum"
	RequiredTag   = "required"
	DefaultTag    = "default"
	ValidationTag = "validate"
	ExplodeTag    = "explode"
)

Fields tags used by optic.

View Source
const DefaultMaxBodyBytes = 256 * 1024

DefaultMaxBodyBytes is the maximum allowed size of a request body in bytes.

Variables

View Source
var (
	Integer  int32
	Long     int64
	Float    float32
	Double   float64
	String   string
	Byte     []byte
	Binary   []byte
	Boolean  bool
	DateTime time.Time
)

Primitive type helpers.

Functions

func DefaultBindHeaderHook

func DefaultBindHeaderHook(c *fiber.Ctx, v reflect.Value) error

func DefaultBindPathHook

func DefaultBindPathHook(c *fiber.Ctx, v reflect.Value) error

func DefaultBindQueryHook

func DefaultBindQueryHook(c *fiber.Ctx, v reflect.Value) error

func DefaultBindingHook

func DefaultBindingHook(c *fiber.Ctx, v reflect.Value) error

DefaultBindingHook is the default binding hook. It uses Gin JSON binding to bind the body parameters of the request to the input object of the handler. Ir teturns an error if Gin binding fails.

func DefaultErrorHook

func DefaultErrorHook(c *fiber.Ctx, e error) (int, interface{})

DefaultErrorHook is the default error hook. It returns a StatusBadRequest with a payload containing the error message.

func DefaultExecHook

func DefaultExecHook(c *fiber.Ctx, h fiber.Handler, fname string) error

DefaultExecHook is the default exec hook. It simply executes the wrapping gin-handler with the given context.

func DefaultRenderHook

func DefaultRenderHook(c *fiber.Ctx, statusCode int, payload interface{})

DefaultRenderHook is the default render hook. It marshals the payload to JSON, or returns an empty body if the payload is nil. If Gin is running in debug mode, the marshalled JSON is indented.

func Deprecated

func Deprecated(deprecated bool) func(*openapi.OperationInfo)

Deprecated marks the operation as deprecated.

func Description

func Description(desc string) func(*openapi.OperationInfo)

Description adds a description to an operation.

func Descriptionf

func Descriptionf(format string, a ...interface{}) func(*openapi.OperationInfo)

Descriptionf adds a description to an operation according to a format specifier.

func GetRoutes

func GetRoutes() map[string]*Route

GetRoutes returns the routes handled by a optic-enabled handler.

func Header(name, desc string, model interface{}) func(*openapi.OperationInfo)

Header adds a header to the operation.

func ID

func ID(id string) func(*openapi.OperationInfo)

ID overrides the operation ID.

func InputModel

func InputModel(model interface{}) func(*openapi.OperationInfo)

InputModel overrides the binding model of the operation.

func MediaType

func MediaType() string

MediaType returns the current media type (MIME) used by the actual render hook.

func OperationFromContext

func OperationFromContext(c *fiber.Ctx) (*openapi.Operation, error)

OperationFromContext returns the OpenAPI operation from the given Fiber context or an error if none is found.

func ParseTagKey

func ParseTagKey(tag string) (string, error)

ParseTagKey parses the given struct tag key and return the name of the field

func RegisterValidation

func RegisterValidation(tagName string, validationFunc validator.Func) error

RegisterValidation registers a custom validation on the validator.Validate instance of the package NOTE: calling this function may instantiate the validator itself. NOTE: this function is not thread safe, since the validator validation registration isn't

func Response

func Response(statusCode, desc string, model interface{}, headers []*openapi.ResponseHeader, example interface{}) func(*openapi.OperationInfo)

Response adds an additional response to the operation.

func ResponseWithExamples

func ResponseWithExamples(statusCode, desc string, model interface{}, headers []*openapi.ResponseHeader, examples map[string]interface{}) func(*openapi.OperationInfo)

ResponseWithExamples is a variant of Response that accept many examples.

func SetBindHeaderHook

func SetBindHeaderHook(bh BindHook)

SetBindQueryHook sets the given hook as the default binding hook.

func SetBindHook

func SetBindHook(bh BindHook)

SetBindHook sets the given hook as the default binding hook.

func SetBindPathHook

func SetBindPathHook(bh BindHook)

SetBindQueryHook sets the given hook as the default binding hook.

func SetBindQueryHook

func SetBindQueryHook(bh BindHook)

SetBindQueryHook sets the given hook as the default binding hook.

func SetErrorHook

func SetErrorHook(eh ErrorHook)

SetErrorHook sets the given hook as the default error handling hook.

func SetExecHook

func SetExecHook(eh ExecHook)

SetExecHook sets the given hook as the default execution hook.

func SetRenderHook

func SetRenderHook(rh RenderHook, mt string)

SetRenderHook sets the given hook as the default rendering hook. The media type is used to generate the OpenAPI specification.

func StatusDescription

func StatusDescription(desc string) func(*openapi.OperationInfo)

StatusDescription sets the default status description of the operation.

func Summary

func Summary(summary string) func(*openapi.OperationInfo)

Summary adds a summary to an operation.

func Summaryf

func Summaryf(format string, a ...interface{}) func(*openapi.OperationInfo)

Summaryf adds a summary to an operation according to a format specifier.

Types

type BindError

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

BindError is an error type returned when optic fails to bind parameters, to differentiate from errors returned by the handlers.

func (BindError) Error

func (be BindError) Error() string

Error implements the builtin error interface for BindError.

func (BindError) ValidationErrors

func (be BindError) ValidationErrors() validator.ValidationErrors

ValidationErrors returns the errors from the validate process.

type BindHook

type BindHook func(*fiber.Ctx, reflect.Value) error

BindHook is the hook called by the wrapping gin-handler when binding an incoming request to the optic-handler's input object.

func GetBindHeaderHook

func GetBindHeaderHook() BindHook

GetBindQueryHook returns the current bind hook.

func GetBindHook

func GetBindHook() BindHook

GetBindHook returns the current bind hook.

func GetBindPathHook

func GetBindPathHook() BindHook

GetBindQueryHook returns the current bind hook.

func GetBindQueryHook

func GetBindQueryHook() BindHook

GetBindQueryHook returns the current bind hook.

type ErrorHook

type ErrorHook func(*fiber.Ctx, error) (int, interface{})

ErrorHook lets you interpret errors returned by your handlers. After analysis, the hook should return a suitable http status code and and error payload. This lets you deeply inspect custom error types.

func GetErrorHook

func GetErrorHook() ErrorHook

GetErrorHook returns the current error hook.

type ExecHook

type ExecHook func(*fiber.Ctx, fiber.Handler, string) error

An ExecHook is the func called to handle a request. The default ExecHook simply calle the wrapping gin-handler with the gin context.

func GetExecHook

func GetExecHook() ExecHook

GetExecHook returns the current execution hook.

type OperationOption

type OperationOption func(*openapi.OperationInfo)

OperationOption represents an option-pattern function used to add informations to an operation.

type Optizz

type Optizz struct {
	*RouterGroup
	// contains filtered or unexported fields
}

Fizz is an abstraction of a Fiber app that wraps the routes handlers with Tonic and generates an OpenAPI 3.0 specification from it.

func New

func New() *Optizz

New creates a new Fizz wrapper for a default Fiber app.

func NewFromApp

func NewFromApp(app *fiber.App) *Optizz

NewFromApp creates a new Fizz wrapper from an existing Fiber app.

func (*Optizz) App

func (f *Optizz) App() *fiber.App

App returns the underlying Fiber app.

func (*Optizz) Errors

func (f *Optizz) Errors() []error

Errors returns the errors that may have occurred during the spec generation.

func (*Optizz) Generator

func (f *Optizz) Generator() *openapi.Generator

Generator returns the underlying OpenAPI generator.

func (*Optizz) OpenAPI

func (f *Optizz) OpenAPI(info *openapi.Info, ct string) fiber.Handler

OpenAPI returns a Fiber HandlerFunc that serves the marshalled OpenAPI specification of the API.

type OptizzHandler

type OptizzHandler struct {
	RouteInfo     *Route
	OperationInfo *openapi.OperationInfo
	Handler       fiber.Handler
}

func Handler

func Handler(fiberHandler interface{}, status int, infos ...OperationOption) *OptizzHandler

Optizz Handler is the wrapper of fiber.Handler with route and operation information.

type RenderHook

type RenderHook func(*fiber.Ctx, int, interface{})

RenderHook is the last hook called by the wrapping gin-handler before returning. It takes the Gin context, the HTTP status code and the response payload as parameters. Its role is to render the payload to the client to the proper format.

func GetRenderHook

func GetRenderHook() RenderHook

GetRenderHook returns the current render hook.

type Route

type Route struct {
	fiber.Route
	// contains filtered or unexported fields
}

A Route contains information about a optic-enabled route.

func GetRouteByHandler

func GetRouteByHandler(h fiber.Handler, ctx *fiber.Ctx) (*Route, error)

GetRouteByHandler returns the route information of the given wrapped handler.

func (*Route) GetDefaultStatusCode

func (r *Route) GetDefaultStatusCode() int

GetDefaultStatusCode returns the default status code of the route.

func (*Route) GetDeprecated

func (r *Route) GetDeprecated() bool

GetDeprecated returns the deprecated flag of the route.

func (*Route) GetDescription

func (r *Route) GetDescription() string

GetDescription returns the description of the route.

func (*Route) GetHandler

func (r *Route) GetHandler() reflect.Value

GetHandler returns the handler of the route.

func (*Route) GetPath

func (r *Route) GetPath() string

GetPath returns the path of the route.

func (*Route) GetSummary

func (r *Route) GetSummary() string

GetSummary returns the summary of the route.

func (*Route) GetTags

func (r *Route) GetTags() []string

GetTags generates a list of tags for the swagger spec from one route definition. It uses the first chunk of the path of the route as the tag (for example, in /foo/bar it will return the "foo" tag), unless specific tags have been defined with optic.Tags

func (*Route) GetVerb

func (r *Route) GetVerb() string

GetVerb returns the HTTP verb of the route.

func (*Route) HandlerName

func (r *Route) HandlerName() string

HandlerName returns the name of the route handler.

func (*Route) HandlerNameWithPackage

func (r *Route) HandlerNameWithPackage() string

HandlerNameWithPackage returns the full name of the rout handler with its package path.

func (*Route) InputType

func (r *Route) InputType() reflect.Type

InputType returns the input type of the handler. If the type is a pointer to a concrete type, it is dereferenced.

func (*Route) OutputType

func (r *Route) OutputType() reflect.Type

OutputType returns the output type of the handler. If the type is a pointer to a concrete type, it is dereferenced.

type RouterGroup

type RouterGroup struct {
	Name        string
	Description string
	// contains filtered or unexported fields
}

RouterGroup is an abstraction of a Fiber router group.

func (*RouterGroup) Delete

func (g *RouterGroup) Delete(path string, handler *OptizzHandler, middlewares ...fiber.Handler) *RouterGroup

func (*RouterGroup) Get

func (g *RouterGroup) Get(path string, handler *OptizzHandler, middlewares ...fiber.Handler) *RouterGroup

func (*RouterGroup) Group

func (g *RouterGroup) Group(path, name, description string, handlers ...fiber.Handler) *RouterGroup

Group creates a new group of routes.

func (*RouterGroup) Handle added in v0.0.2

func (g *RouterGroup) Handle(path, method string, handler *OptizzHandler, middlewares ...fiber.Handler) *RouterGroup

func (*RouterGroup) Head

func (g *RouterGroup) Head(path string, handler *OptizzHandler, middlewares ...fiber.Handler) *RouterGroup

func (*RouterGroup) Options

func (g *RouterGroup) Options(path string, handler *OptizzHandler, middlewares ...fiber.Handler) *RouterGroup

func (*RouterGroup) Patch

func (g *RouterGroup) Patch(path string, handler *OptizzHandler, middlewares ...fiber.Handler) *RouterGroup

func (*RouterGroup) Post

func (g *RouterGroup) Post(path string, handler *OptizzHandler, middlewares ...fiber.Handler) *RouterGroup

func (*RouterGroup) Put

func (g *RouterGroup) Put(path string, handler *OptizzHandler, middlewares ...fiber.Handler) *RouterGroup

func (*RouterGroup) Trace

func (g *RouterGroup) Trace(path string, handler *OptizzHandler, middlewares ...fiber.Handler) *RouterGroup

func (*RouterGroup) Use

func (g *RouterGroup) Use(handlers ...fiber.Handler)

Use adds middleware to the group.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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