goapi

package module
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2023 License: MIT Imports: 17 Imported by: 0

README

Overview

A lightweight opinionated router to bridge function call and http api. It helps to standardize the way to define input and output of a service.

Features

  • Auto generate openapi doc from code reflection
  • Use function signature to define input and output
  • Type safe without struct tags

Usage

Hello world example: main.go.

Check the examples folder.

Read the tests for details.

Benchmark

Without any optimization, goapi is about 7% slower than echo for the simplest usage. This benchmark is only for avoiding drastic performance changes, the real performance depends on the complexity of the service.

go test -bench=. -benchmem ./lib/bench
goos: darwin
goarch: arm64
pkg: github.com/NaturalSelectionLabs/goapi/lib/bench
Benchmark_goapi-12         34472             33856 ns/op            8448 B/op        114 allocs/op
Benchmark_echo-12          36729             31175 ns/op            6776 B/op         82 allocs/op
PASS
ok      github.com/NaturalSelectionLabs/goapi/lib/bench 5.711s

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrMissingParam = errors.New("missing parameter in request")

Functions

func Interface added in v0.2.0

func Interface(i any, ts ...any) *vary.Interface

Interface create a interface set of i. ts are the types that implement i. For golang runtime we can't reflect all the implementations of an interface, with it goapi can find out all the possible response type of an endpoint.

Types

type ConfigOperation

type ConfigOperation func(op *Operation)

func Description

func Description(d string) ConfigOperation

Description for the operation.

func OperationID added in v0.3.0

func OperationID(id string) ConfigOperation

OperationID for the operation.

func Security added in v0.3.1

func Security(security ...map[string][]string) ConfigOperation

Security for the operation.

func Summary added in v0.3.0

func Summary(s string) ConfigOperation

Summary for the operation.

func Tags added in v0.3.0

func Tags(tags ...string) ConfigOperation

Tags for the operation.

type Descriptioner added in v0.3.0

type Descriptioner interface {
	Description() string
}

type FormatResponse added in v0.4.0

type FormatResponse func(openapi.ResponseFormat) any

type Group

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

func New

func New() *Group

New is a shortcut for:

NewRouter().Group("")

func (*Group) Add

func (g *Group) Add(
	method openapi.Method, path string, handler any, opts ...ConfigOperation,
)

func (*Group) DELETE

func (g *Group) DELETE(path string, handler any, opts ...ConfigOperation)

func (*Group) GET

func (g *Group) GET(path string, handler any, opts ...ConfigOperation)

func (*Group) Group

func (g *Group) Group(prefix string) *Group

Group creates a sub group of current group.

func (*Group) HEAD

func (g *Group) HEAD(path string, handler any, opts ...ConfigOperation)

func (*Group) Handler added in v0.2.0

func (g *Group) Handler(h http.Handler) http.Handler

Use is a shortcut for Router.Handler.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, handler any, opts ...ConfigOperation)

func (*Group) OpenAPI

func (r *Group) OpenAPI(schemas *jschema.Schemas) *openapi.Document

func (*Group) PATCH

func (g *Group) PATCH(path string, handler any, opts ...ConfigOperation)

func (*Group) POST

func (g *Group) POST(path string, handler any, opts ...ConfigOperation)

func (*Group) PUT

func (g *Group) PUT(path string, handler any, opts ...ConfigOperation)

func (*Group) Router added in v0.5.0

func (g *Group) Router() *Router

func (*Group) Server

func (g *Group) Server() http.Handler

Handler is a shortcut for Router.Handler.

func (*Group) Shutdown added in v0.2.0

func (g *Group) Shutdown(ctx context.Context) error

Shutdown is a shortcut for Router.Shutdown.

func (*Group) Start added in v0.2.0

func (g *Group) Start(addr string) error

Start is a shortcut for Router.Start.

func (*Group) Use

func (g *Group) Use(m middlewares.Middleware)

Use is a shortcut for Router.Use.

type InBody

type InBody struct{}

type InHeader

type InHeader struct{}

type InURL

type InURL struct{}

type Operation

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

Operation is a handler for a specific HTTP method and path. We use reflection to constrain the handler function signature, to make it follow the openapi spec.

func (*Operation) Handler

func (op *Operation) Handler(next http.Handler) http.Handler

type OperationMeta

type OperationMeta struct {
	// Summary is used for display in the openapi UI.
	Summary string
	// Description is used for display in the openapi UI.
	Description string
	// OperationID is a unique string used to identify an individual operation.
	// This can be used by tools and libraries to provide functionality for
	// referencing and calling the operation from different parts of your application.
	OperationID string
	// Tags are used for grouping operations together for display in the openapi UI.
	Tags []string
	// Security is a declaration of which security mechanisms can be used for this operation.
	Security []map[string][]string
}

type Params

type Params interface {
	// contains filtered or unexported methods
}

type Path

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

Path helps to handle openapi path pattern.

type Response

type Response interface {
	// contains filtered or unexported methods
}

Response is an interface that represents a response object.

type Router

type Router struct {
	// FormatResponse is a function that formats the response.
	// The default format the structs implement [ResponseFormat].
	// You can use this function override the default format.
	FormatResponse FormatResponse
	// Validate the parameters of each request.
	Validate func(v interface{}) *openapi.Error
	// contains filtered or unexported fields
}

Router itself is a middleware.

func NewRouter

func NewRouter() *Router

func (*Router) Group

func (r *Router) Group(prefix string) *Group

Group creates a new group with the given prefix.

func (*Router) Handler

func (r *Router) Handler(next http.Handler) http.Handler

func (*Router) OpenAPI

func (r *Router) OpenAPI(schemas *jschema.Schemas) *openapi.Document

OpenAPI returns the OpenAPI doc of the router. You can use json.Marshal to convert it to a JSON string.

func (*Router) ServerHandler added in v0.2.0

func (r *Router) ServerHandler() http.Handler

ServerHandler with a 404 middleware at the end.

func (*Router) Shutdown added in v0.2.0

func (r *Router) Shutdown(ctx context.Context) error

Shutdown the server.

func (*Router) Start added in v0.2.0

func (r *Router) Start(addr string) error

Start listen on addr with the Router.ServerHandler.

func (*Router) Use

func (r *Router) Use(middlewares ...middlewares.Middleware)

Use a middleware to the router.

type StatusAccepted

type StatusAccepted struct{}

StatusAccepted 202.

type StatusAlreadyReported

type StatusAlreadyReported struct{}

StatusAlreadyReported 208.

type StatusBadGateway

type StatusBadGateway struct{}

StatusBadGateway 502.

type StatusBadRequest

type StatusBadRequest struct{}

StatusBadRequest 400.

type StatusConflict

type StatusConflict struct{}

StatusConflict 409.

type StatusContinue

type StatusContinue struct{}

StatusContinue 100.

type StatusCreated

type StatusCreated struct{}

StatusCreated 201.

type StatusEarlyHints

type StatusEarlyHints struct{}

StatusEarlyHints 103.

type StatusExpectationFailed

type StatusExpectationFailed struct{}

StatusExpectationFailed 417.

type StatusFailedDependency

type StatusFailedDependency struct{}

StatusFailedDependency 424.

type StatusForbidden

type StatusForbidden struct{}

StatusForbidden 403.

type StatusFound

type StatusFound struct{}

StatusFound 302.

type StatusGatewayTimeout

type StatusGatewayTimeout struct{}

StatusGatewayTimeout 504.

type StatusGone

type StatusGone struct{}

StatusGone 410.

type StatusHTTPVersionNotSupported

type StatusHTTPVersionNotSupported struct{}

StatusHTTPVersionNotSupported 505.

type StatusIMUsed

type StatusIMUsed struct{}

StatusIMUsed 226.

type StatusInsufficientStorage

type StatusInsufficientStorage struct{}

StatusInsufficientStorage 507.

type StatusInternalServerError

type StatusInternalServerError struct{}

StatusInternalServerError 500.

type StatusLengthRequired

type StatusLengthRequired struct{}

StatusLengthRequired 411.

type StatusLocked

type StatusLocked struct{}

StatusLocked 423.

type StatusLoopDetected

type StatusLoopDetected struct{}

StatusLoopDetected 508.

type StatusMethodNotAllowed

type StatusMethodNotAllowed struct{}

StatusMethodNotAllowed 405.

type StatusMisdirectedRequest

type StatusMisdirectedRequest struct{}

StatusMisdirectedRequest 421.

type StatusMovedPermanently

type StatusMovedPermanently struct{}

StatusMovedPermanently 301.

type StatusMultiStatus

type StatusMultiStatus struct{}

StatusMultiStatus 207.

type StatusMultipleChoices

type StatusMultipleChoices struct{}

StatusMultipleChoices 300.

type StatusNetworkAuthenticationRequired

type StatusNetworkAuthenticationRequired struct{}

StatusNetworkAuthenticationRequired 511.

type StatusNoContent

type StatusNoContent struct{}

StatusNoContent 204.

type StatusNonAuthoritativeInfo

type StatusNonAuthoritativeInfo struct{}

StatusNonAuthoritativeInfo 203.

type StatusNotAcceptable

type StatusNotAcceptable struct{}

StatusNotAcceptable 406.

type StatusNotExtended

type StatusNotExtended struct{}

StatusNotExtended 510.

type StatusNotFound

type StatusNotFound struct{}

StatusNotFound 404.

type StatusNotImplemented

type StatusNotImplemented struct{}

StatusNotImplemented 501.

type StatusNotModified

type StatusNotModified struct{}

StatusNotModified 304.

type StatusOK

type StatusOK struct{}

StatusOK 200.

type StatusPartialContent

type StatusPartialContent struct{}

StatusPartialContent 206.

type StatusPaymentRequired

type StatusPaymentRequired struct{}

StatusPaymentRequired 402.

type StatusPermanentRedirect

type StatusPermanentRedirect struct{}

StatusPermanentRedirect 308.

type StatusPreconditionFailed

type StatusPreconditionFailed struct{}

StatusPreconditionFailed 412.

type StatusPreconditionRequired

type StatusPreconditionRequired struct{}

StatusPreconditionRequired 428.

type StatusProcessing

type StatusProcessing struct{}

StatusProcessing 102.

type StatusProxyAuthRequired

type StatusProxyAuthRequired struct{}

StatusProxyAuthRequired 407.

type StatusRequestEntityTooLarge

type StatusRequestEntityTooLarge struct{}

StatusRequestEntityTooLarge 413.

type StatusRequestHeaderFieldsTooLarge

type StatusRequestHeaderFieldsTooLarge struct{}

StatusRequestHeaderFieldsTooLarge 431.

type StatusRequestTimeout

type StatusRequestTimeout struct{}

StatusRequestTimeout 408.

type StatusRequestURITooLong

type StatusRequestURITooLong struct{}

StatusRequestURITooLong 414.

type StatusRequestedRangeNotSatisfiable

type StatusRequestedRangeNotSatisfiable struct{}

StatusRequestedRangeNotSatisfiable 416.

type StatusResetContent

type StatusResetContent struct{}

StatusResetContent 205.

type StatusSeeOther

type StatusSeeOther struct{}

StatusSeeOther 303.

type StatusServiceUnavailable

type StatusServiceUnavailable struct{}

StatusServiceUnavailable 503.

type StatusSwitchingProtocols

type StatusSwitchingProtocols struct{}

StatusSwitchingProtocols 101.

type StatusTeapot

type StatusTeapot struct{}

StatusTeapot 418.

type StatusTemporaryRedirect

type StatusTemporaryRedirect struct{}

StatusTemporaryRedirect 307.

type StatusTooEarly

type StatusTooEarly struct{}

StatusTooEarly 425.

type StatusTooManyRequests

type StatusTooManyRequests struct{}

StatusTooManyRequests 429.

type StatusUnauthorized

type StatusUnauthorized struct{}

StatusUnauthorized 401.

type StatusUnavailableForLegalReasons

type StatusUnavailableForLegalReasons struct{}

StatusUnavailableForLegalReasons 451.

type StatusUnprocessableEntity

type StatusUnprocessableEntity struct{}

StatusUnprocessableEntity 422.

type StatusUnsupportedMediaType

type StatusUnsupportedMediaType struct{}

StatusUnsupportedMediaType 415.

type StatusUpgradeRequired

type StatusUpgradeRequired struct{}

StatusUpgradeRequired 426.

type StatusUseProxy

type StatusUseProxy struct{}

StatusUseProxy 305.

type StatusVariantAlsoNegotiates

type StatusVariantAlsoNegotiates struct{}

StatusVariantAlsoNegotiates 506.

Jump to

Keyboard shortcuts

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