openapimux

package module
v0.0.0-...-961128b Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2019 License: MIT Imports: 4 Imported by: 0

README

OpenAPIMux

OpenAPIMux is a "schema-first" HTTP router. It takes one or multiple OpenAPI (Swagger) schema files as an input and then matches, validates and handles all incoming HTTP based on these schemas. Under the hood, it uses kin-openapi for OpenAPI schema parsing and validation.

Motivation

OpenAPI offers a great way of documenting API. However, none of existing go routers offers "schema first" approach. In each router, you need to initialize a list of available routes and then do the request validation manually. OpenAPIMux fills this gap by allowing to initialize a router directly from the OpenAPI schema definition file.

Features

  • Works with both OpenAPI 3.0 and OpenAPI 2.0 (aka Swagger). As well as both json and yaml schemas
  • Multiple OpenAPI schema files can be used at the same router to support API versioning
  • Implements http.Handler interface, so it is compatible with the standard http.ServeMux
  • Supports global level http.Handler middlewares, so it is compatible with third-party middlewares
  • Supports custom error handler for more control

Routing

  • operationId attribute of an OpenAPI path is used to resolve it to an appropriate handler
  • OpenAPIMux can encapsulate one or more swagger routers. Each router could be created from an OpenAPI schema file or directly as a swagger object
  • To handle multiple versions, use the servers.url attribute in OpenAPI schema. Eg
servers:
 - url: "/v1.2"
  • When finding a matching route, routers with servers attribute set take priority

Install

go get -u github.com/MNFGroup/openapimux

Full Example

Assuming openapi.yaml has the following schema

openapi: 3.0.0

paths:
  /foo:
    get:
      operationId: getFoo

It will create and start a server on 8080

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/go-chi/chi/middleware"
)

type fooHandler struct{}

func (f fooHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello")
}

func main() {
	r, err := NewRouter("./openapi.yaml")
	if err != nil {
		panic(err)
	}

	r.UseHandlers(map[string]http.Handler{
		"getFoo": fooHandler{},
	})

	r.UseMiddleware(
		middleware.Recoverer,
		middleware.RequestID,
		middleware.DefaultCompress,
	)

	r.ErrorHandler = func(w http.ResponseWriter, r *http.Request, data string, code int) {
		w.WriteHeader(code)
		if code == http.StatusInternalServerError {
			fmt.Println("Fatal:", data)
			w.Write([]byte("Oops"))
		} else {
			w.Write([]byte(data))
		}
	}

	log.Fatal(http.ListenAndServe(":8080", r))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func PathParam

func PathParam(r *http.Request, key string) string

PathParam returns the in-context path params for a request by name.

func Respond

func Respond(w http.ResponseWriter, r *http.Request, data string, code int)

Respond sends HTTP response

func WithPathParams

func WithPathParams(r *http.Request, pathParams map[string]string) *http.Request

WithPathParams sets the in-context path params for a request.

Types

type OpenAPIMux

type OpenAPIMux struct {
	Routers       *openapi3filter.Routers
	ErrorHandler  func(http.ResponseWriter, *http.Request, string, int)
	DetailedError bool
	// contains filtered or unexported fields
}

OpenAPIMux is a "schema first" HTTP router. It takes one or multiple OpenAPI schema files as an input and then matches, validates and handles all incoming HTTP based on these schemas. Under the hood, it uses https://github.com/getkin/kin-openapi/ for OpenAPI schema parsing and validation.

Notes on routing: * Routers is a []*Router slice * Each router could be created from a openapi schema file or directly swagger object * "operationId" attribute of a path is used to resolve it to a handler * Multiple routers could be used to handle multiple schema versions * To handle multiple versions, use "servers.url" attribute in openapi schema. Eg servers:

  • url: "/v1.2"

* When finding a matching route, routers with "servers" attribute set take priority

func NewRouter

func NewRouter(apis ...string) (*OpenAPIMux, error)

NewRouter creates a OpenAPIMux from API definitions

func (*OpenAPIMux) ServeHTTP

func (sr *OpenAPIMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the single method of the http.Handler interface that makes swagger router interoperable with the standard library. It will run request through all regestered middlewares and finally pass to handler.

func (*OpenAPIMux) UseHandlers

func (sr *OpenAPIMux) UseHandlers(handlers map[string]http.Handler)

UseHandlers appends a handlers to the handlers stack.

func (*OpenAPIMux) UseMiddleware

func (sr *OpenAPIMux) UseMiddleware(middlewares ...func(http.Handler) http.Handler)

UseMiddleware appends a middleware handler to the middleware stack.

Jump to

Keyboard shortcuts

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