OpenAPI 2.0 (aka Swagger) utils for Golang.
Clone or download
Latest commit 3921dca Oct 1, 2018
Permalink
Failed to load latest commit information.
.circleci Rework library concepts Sep 25, 2018
_examples Add chi adapter Sep 26, 2018
adapter Minor fixes Oct 1, 2018
cmd/oas-expand Router now accepts document instead of spec Mar 20, 2018
convert Get array from string based on collectionFormat Jul 6, 2018
e2e Add chi adapter Sep 26, 2018
formats Rework CI Mar 5, 2018
testdata Add Document wrapper Jun 2, 2018
validate Enable partial time and custom validators Dec 19, 2017
.gitignore Rework library concepts Sep 25, 2018
.gometalinter.json Fix linter issues Jun 2, 2018
CHANGELOG.md Minor fixes Oct 1, 2018
Gopkg.lock Add chi adapter Sep 26, 2018
Gopkg.toml Rework library concepts Sep 25, 2018
LICENSE Initial commit Aug 30, 2017
Makefile Add e2e test for middleware order Jun 2, 2018
README.md Minor fixes Oct 1, 2018
basis_resolving.go Add chi adapter Sep 26, 2018
decode.go Rework library concepts Sep 25, 2018
decode_integration_test.go Rework library concepts Sep 25, 2018
decode_test.go Rework library concepts Sep 25, 2018
doc.go Rework library concepts Sep 25, 2018
error.go Fix linter issues; export path param context middleware Sep 25, 2018
go_openapi_wrappers.go Add Operation wrapper Jun 2, 2018
load.go Rework library concepts Sep 25, 2018
load_test.go Add Document wrapper Jun 2, 2018
media.go Set content-type comparison to case-insensitive Sep 26, 2018
middleware.go Fix linter issues; export path param context middleware Sep 25, 2018
middleware_media_type.go Set content-type comparison to case-insensitive Sep 26, 2018
middleware_media_type_test.go Rework library concepts Sep 25, 2018
middleware_path_params.go Fix linter issues; export path param context middleware Sep 25, 2018
middleware_path_params_test.go Fix linter issues; export path param context middleware Sep 25, 2018
middleware_query.go Rework library concepts Sep 25, 2018
middleware_query_test.go Rework library concepts Sep 25, 2018
middleware_request_body.go Rework library concepts Sep 25, 2018
middleware_request_body_test.go Rework library concepts Sep 25, 2018
middleware_response_body.go Rework library concepts Sep 25, 2018
middleware_response_body_test.go Rework library concepts Sep 25, 2018
operation.go Fix linter issues; export path param context middleware Sep 25, 2018
problem.go Fix linter issues; export path param context middleware Sep 25, 2018
router.go Rework library concepts Sep 25, 2018
spec_handlers.go Rework library concepts Sep 25, 2018
spec_handlers_test.go Rework library concepts Sep 25, 2018
testing_test.go Fix linter issues; export path param context middleware Sep 25, 2018
util_response.go Rework library concepts Sep 25, 2018
util_response_test.go Rework library concepts Sep 25, 2018

README.md

oas2

GoDoc CircleCI codecov Go Report Card GitHub release License MIT

Note that this is not stable yet. In accordance with semantic versioning, the API can change between any minor versions. Use a vendoring tool of your preference to lock an exact release version.

Package oas2 provides utilities for building APIs using the OpenAPI 2.0 specification (aka Swagger) in Go idiomatic way on top of net/http.

You don't need to learn any special framework or write net/http-incompatible code - just delegate request validation, request parameters decoding and other routines to this library - and focus on your application logic.

This package is built on top of OpenAPI Initiative golang toolkit.

Should I have an OpenAPI specification for my API?

If you don't have a spec for your API yet - it's definitely worth it to create one. The specification itself provides many useful things, such as documentation, usage examples, and others. Learn more about OpenAPI and its purposes. The great thing is that it is compatible with many tools for developers and consumers; Swagger Toolkit is the most popular set of utilities for OpenAPI.

This package offers an integration of the spec with your code. And tightly coupling your code with the spec is a good thing - you create a strong contract for API consumers, and any changes to your API will be clearly reflected in the spec. You will see many benefits, such as distinctly recognize the situation when you need to increase the major version of your API because of incompatible changes.

Features

Router from a spec

This package provides an easy way to automatically create a router supporting all resources from your OpenAPI specification file. The underlying router is only your choice - you can use gorilla/mux, chi or any other.

Let's dive into a simple example.

Given a spec: petstore.yaml

First of all, load your spec in your app (note that though package import path ends in oas2, the package namespace is actually oas):

import "github.com/hypnoglow/oas2"

// ...

// specPath is a path to your spec file.
doc, _ := oas.LoadFile(specPath)

Next, create an operation handler. Let's define a handler for findPetsByStatus operation:

type FindPetsByStatusHandler struct {
	storage PetStorage
}

func (h FindPetsByStatusHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	statuses := req.URL.Query()["status"]

	pets := h.storage.FindByStatus(statuses)

	_ = json.NewEncoder(w).Encode(pets)
}
handlers := oas.OperationHandlers{
    "findPetsByStatus":    findPetsByStatus{},
}

Define what options (logger, middleware) you will use:

logger := logrus.New()
logger.SetLevel(logrus.DebugLevel)
queryValidator := oas.QueryValidator(errHandler)

Create a router:

router, _ := oas.NewRouter(
    doc, 
    handlers, 
    oas.DebugLog(logger.Debugf), 
    oas.Use(queryValidator)
)

Then you can use your router as an argument for http.ListenAndServe or even as a subrouter for the other router.

http.ListenAndServe(":8080", router)

Now the server handles requests based on the paths defined in the given spec. It validates request query parameters against the spec and runs errHandler func if any error occured during validation. The router also sets the operation identifier to each request's context, so it can be used in a handler or any custom middleware.

See the full example for the complete code.

Decode query parameters to a struct

Given request query parameters: ?name=John&age=27

Given OpenAPI v2 (swagger) spec:

...
parameters:
- name: name
  type: string
- name: age
  type: integer
  format: int32
- name: loves_apples
  type: bool
  default: true
...

In your Go code you create a struct:

type Member struct {
	Name        string `oas:"name"`
	Age         int32  `oas:"age"`
	LovesApples bool   `oas:"loves_apples"`
}

And populate it:

var m Member 
oas.DecodeQuery(req, &m)

fmt.Printf("%#v", m) // Member{Name:"John", Age:27, LovesApples:true}

Note that it works only with oas router, because it needs to extract operation spec from the request. To use custom parameters spec, use oas.DecodeQueryParams(). See godoc example for details.

Pluggable formats & validators

The specification allows to have custom formats and to validate against them.

This package provides the following custom formats and validators:

You can also implement your custom format and validator for it, and then register it:

validate.RegisterFormat("myformat", &MyCustomFormat{}, ValidateMyCustomFormat)

License

MIT.