goapi

package module
v0.9.11 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2024 License: MIT Imports: 18 Imported by: 2

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.

RPC style 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/ysmood/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/ysmood/goapi/lib/bench 5.711s

Documentation

Overview

Package goapi is a lightweight opinionated router to bridge function call and http api.

Index

Constants

View Source
const (
	// TagResponse is one tag name for Data field.
	TagResponse = "response"
	// TagResponseDirect is one value for [TagResponse].
	TagResponseDirect = "direct"
)

Variables

View Source
var Interfaces = vary.NewInterfaces()

Interfaces is the global interface set.

Functions

func AddInterfaces

func AddInterfaces(is vary.Interfaces)

AddInterfaces to the global interface set.

func Interface

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 ConfigOpenAPI

type ConfigOpenAPI func(doc *openapi.Operation)

ConfigOpenAPI is a function to modify the generated OpenAPI doc.

type ContentTyper

type ContentTyper interface {
	ContentType() string
}

ContentTyper is an interface that is use to specify the http Content-Type in openapi.

type DataStream

type DataStream io.Reader

DataStream is a flag for binary response body. When Data field in the response struct is of this type, the response body will be written directly to the http.ResponseWriter.

type Descriptioner

type Descriptioner interface {
	Description() string
}

Descriptioner is an interface that is use to specify the description in openapi.

type Group

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

Group of handlers with the same url path prefix.

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 OperationHandler) *Operation

Add adds a new http handler to the group. If a request matches the path and method, the handler will be called. The router will ignore the trailing slash of the path if a path without trailing slash has not been defined.

func (*Group) DELETE

func (g *Group) DELETE(path string, handler OperationHandler) *Operation

DELETE is a shortcut for Group.Add.

func (*Group) GET

func (g *Group) GET(path string, handler OperationHandler) *Operation

GET is a shortcut for Group.Add.

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 OperationHandler) *Operation

HEAD is a shortcut for Group.Add.

func (*Group) Handler

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

Handler is a shortcut for Router.Handler.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, handler OperationHandler) *Operation

OPTIONS is a shortcut for Group.Add.

func (*Group) OpenAPI

func (g *Group) OpenAPI() *openapi.Document

OpenAPI is a shortcut for Router.OpenAPI.

func (*Group) PATCH

func (g *Group) PATCH(path string, handler OperationHandler) *Operation

PATCH is a shortcut for Group.Add.

func (*Group) POST

func (g *Group) POST(path string, handler OperationHandler) *Operation

POST is a shortcut for Group.Add.

func (*Group) PUT

func (g *Group) PUT(path string, handler OperationHandler) *Operation

PUT is a shortcut for Group.Add.

func (*Group) Prefix

func (g *Group) Prefix() string

Prefix returns the prefix of the group.

func (*Group) Router

func (g *Group) Router() *Router

Router returns the router of the group.

func (*Group) Run added in v0.9.5

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

Run is a shortcut for Router.Run.

func (*Group) Server

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

Server is a shortcut for Router.Handler.

func (*Group) Shutdown

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

Shutdown is a shortcut for Router.Shutdown.

func (*Group) Use

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

Use is similar to Router.Use but with he group prefix.

type InHeader

type InHeader struct{}

InHeader is a flag that can be embedded into a struct to mark it as a container for request header parameters.

type InURL

type InURL struct{}

InURL is a flag that can be embedded into a struct to mark it as a container for request url parameters.

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 Add

func Add[P, S any](g *Group, fn func(P) S) *Operation

Add is a shortcut for Group.Add for a random golang function. It only accepts POST request method. It will use the function name as the url path name. It will treat the input and output of the function as the request and response body.

func (*Operation) Handler

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

Handler implements the middlewares.Middleware interface.

func (*Operation) OpenAPI

func (op *Operation) OpenAPI(config ConfigOpenAPI)

OpenAPI sets the config function to modify the generated OpenAPI doc.

type OperationHandler

type OperationHandler any

OperationHandler is a function to handle input and output of a http operation.

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 {
	Schemas jschema.Schemas
	// contains filtered or unexported fields
}

Router for routing http requests to handlers. It implements the middlewares.Middleware interface.

func NewRouter

func NewRouter() *Router

NewRouter creates a new router.

func (*Router) AddFormatChecker

func (r *Router) AddFormatChecker(name string, c gojsonschema.FormatChecker)

AddFormatChecker for json schema validation. Such as a struct:

type User struct {
	ID string `format:"my-id"`
}

You can add a format checker for "id" like:

AddFormatChecker("my-id", checker)

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

Handler implements the middlewares.Middleware interface. It makes the router itself a middleware.

func (*Router) OpenAPI

func (r *Router) OpenAPI() *openapi.Document

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

func (*Router) Run added in v0.9.7

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

Run listen on addr with the Router.ServerHandler.

func (*Router) ServerHandler

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

ServerHandler with a 404 middleware at the end.

func (*Router) Shutdown

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

Shutdown the server.

func (*Router) Use

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

Use a middleware to the router.

type StatusAccepted

type StatusAccepted struct{}

StatusAccepted represents http status code 202.

type StatusAlreadyReported

type StatusAlreadyReported struct{}

StatusAlreadyReported represents http status code 208.

type StatusBadGateway

type StatusBadGateway struct{}

StatusBadGateway represents http status code 502.

type StatusBadRequest

type StatusBadRequest struct{}

StatusBadRequest represents http status code 400.

type StatusConflict

type StatusConflict struct{}

StatusConflict represents http status code 409.

type StatusContinue

type StatusContinue struct{}

StatusContinue represents http status code 100.

type StatusCreated

type StatusCreated struct{}

StatusCreated represents http status code 201.

type StatusEarlyHints

type StatusEarlyHints struct{}

StatusEarlyHints represents http status code 103.

type StatusExpectationFailed

type StatusExpectationFailed struct{}

StatusExpectationFailed represents http status code 417.

type StatusFailedDependency

type StatusFailedDependency struct{}

StatusFailedDependency represents http status code 424.

type StatusForbidden

type StatusForbidden struct{}

StatusForbidden represents http status code 403.

type StatusFound

type StatusFound struct{}

StatusFound represents http status code 302.

type StatusGatewayTimeout

type StatusGatewayTimeout struct{}

StatusGatewayTimeout represents http status code 504.

type StatusGone

type StatusGone struct{}

StatusGone represents http status code 410.

type StatusHTTPVersionNotSupported

type StatusHTTPVersionNotSupported struct{}

StatusHTTPVersionNotSupported represents http status code 505.

type StatusIMUsed

type StatusIMUsed struct{}

StatusIMUsed represents http status code 226.

type StatusInsufficientStorage

type StatusInsufficientStorage struct{}

StatusInsufficientStorage represents http status code 507.

type StatusInternalServerError

type StatusInternalServerError struct{}

StatusInternalServerError represents http status code 500.

type StatusLengthRequired

type StatusLengthRequired struct{}

StatusLengthRequired represents http status code 411.

type StatusLocked

type StatusLocked struct{}

StatusLocked represents http status code 423.

type StatusLoopDetected

type StatusLoopDetected struct{}

StatusLoopDetected represents http status code 508.

type StatusMethodNotAllowed

type StatusMethodNotAllowed struct{}

StatusMethodNotAllowed represents http status code 405.

type StatusMisdirectedRequest

type StatusMisdirectedRequest struct{}

StatusMisdirectedRequest represents http status code 421.

type StatusMovedPermanently

type StatusMovedPermanently struct{}

StatusMovedPermanently represents http status code 301.

type StatusMultiStatus

type StatusMultiStatus struct{}

StatusMultiStatus represents http status code 207.

type StatusMultipleChoices

type StatusMultipleChoices struct{}

StatusMultipleChoices represents http status code 300.

type StatusNetworkAuthenticationRequired

type StatusNetworkAuthenticationRequired struct{}

StatusNetworkAuthenticationRequired represents http status code 511.

type StatusNoContent

type StatusNoContent struct{}

StatusNoContent represents http status code 204.

type StatusNonAuthoritativeInfo

type StatusNonAuthoritativeInfo struct{}

StatusNonAuthoritativeInfo represents http status code 203.

type StatusNotAcceptable

type StatusNotAcceptable struct{}

StatusNotAcceptable represents http status code 406.

type StatusNotExtended

type StatusNotExtended struct{}

StatusNotExtended represents http status code 510.

type StatusNotFound

type StatusNotFound struct{}

StatusNotFound represents http status code 404.

type StatusNotImplemented

type StatusNotImplemented struct{}

StatusNotImplemented represents http status code 501.

type StatusNotModified

type StatusNotModified struct{}

StatusNotModified represents http status code 304.

type StatusOK

type StatusOK struct{}

StatusOK represents http status code 200.

type StatusPartialContent

type StatusPartialContent struct{}

StatusPartialContent represents http status code 206.

type StatusPaymentRequired

type StatusPaymentRequired struct{}

StatusPaymentRequired represents http status code 402.

type StatusPermanentRedirect

type StatusPermanentRedirect struct{}

StatusPermanentRedirect represents http status code 308.

type StatusPreconditionFailed

type StatusPreconditionFailed struct{}

StatusPreconditionFailed represents http status code 412.

type StatusPreconditionRequired

type StatusPreconditionRequired struct{}

StatusPreconditionRequired represents http status code 428.

type StatusProcessing

type StatusProcessing struct{}

StatusProcessing represents http status code 102.

type StatusProxyAuthRequired

type StatusProxyAuthRequired struct{}

StatusProxyAuthRequired represents http status code 407.

type StatusRequestEntityTooLarge

type StatusRequestEntityTooLarge struct{}

StatusRequestEntityTooLarge represents http status code 413.

type StatusRequestHeaderFieldsTooLarge

type StatusRequestHeaderFieldsTooLarge struct{}

StatusRequestHeaderFieldsTooLarge represents http status code 431.

type StatusRequestTimeout

type StatusRequestTimeout struct{}

StatusRequestTimeout represents http status code 408.

type StatusRequestURITooLong

type StatusRequestURITooLong struct{}

StatusRequestURITooLong represents http status code 414.

type StatusRequestedRangeNotSatisfiable

type StatusRequestedRangeNotSatisfiable struct{}

StatusRequestedRangeNotSatisfiable represents http status code 416.

type StatusResetContent

type StatusResetContent struct{}

StatusResetContent represents http status code 205.

type StatusSeeOther

type StatusSeeOther struct{}

StatusSeeOther represents http status code 303.

type StatusServiceUnavailable

type StatusServiceUnavailable struct{}

StatusServiceUnavailable represents http status code 503.

type StatusSwitchingProtocols

type StatusSwitchingProtocols struct{}

StatusSwitchingProtocols represents http status code 101.

type StatusTeapot

type StatusTeapot struct{}

StatusTeapot represents http status code 418.

type StatusTemporaryRedirect

type StatusTemporaryRedirect struct{}

StatusTemporaryRedirect represents http status code 307.

type StatusTooEarly

type StatusTooEarly struct{}

StatusTooEarly represents http status code 425.

type StatusTooManyRequests

type StatusTooManyRequests struct{}

StatusTooManyRequests represents http status code 429.

type StatusUnauthorized

type StatusUnauthorized struct{}

StatusUnauthorized represents http status code 401.

type StatusUnavailableForLegalReasons

type StatusUnavailableForLegalReasons struct{}

StatusUnavailableForLegalReasons represents http status code 451.

type StatusUnprocessableEntity

type StatusUnprocessableEntity struct{}

StatusUnprocessableEntity represents http status code 422.

type StatusUnsupportedMediaType

type StatusUnsupportedMediaType struct{}

StatusUnsupportedMediaType represents http status code 415.

type StatusUpgradeRequired

type StatusUpgradeRequired struct{}

StatusUpgradeRequired represents http status code 426.

type StatusUseProxy

type StatusUseProxy struct{}

StatusUseProxy represents http status code 305.

type StatusVariantAlsoNegotiates

type StatusVariantAlsoNegotiates struct{}

StatusVariantAlsoNegotiates represents http status code 506.

Directories

Path Synopsis
lib
examples/basic
Package main ...
Package main ...
examples/hello-world
Package main .
Package main .
examples/rpc
Package main .
Package main .
flat-fields
Package ff contains a struct flattening utility.
Package ff contains a struct flattening utility.
gen-status-code
Package main ...
Package main ...
middlewares
Package middlewares contains common middlewares helpers.
Package middlewares contains common middlewares helpers.
middlewares/apidoc
Package apidoc contains a middleware to serve the OpenAPI document.
Package apidoc contains a middleware to serve the OpenAPI document.
middlewares/calm
Package calm implements a middleware to recover from panic.
Package calm implements a middleware to recover from panic.
openapi
Package openapi contains all the necessary types of an OpenAPI document.
Package openapi contains all the necessary types of an OpenAPI document.

Jump to

Keyboard shortcuts

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