-
Notifications
You must be signed in to change notification settings - Fork 0
/
openapi2.go
59 lines (53 loc) · 1.65 KB
/
openapi2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package nvalid
import (
"encoding/json"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"github.com/getkin/kin-openapi/openapi2"
"github.com/getkin/kin-openapi/openapi2conv"
"github.com/ghodss/yaml"
"github.com/muir/nject"
"github.com/muir/nvelope"
"github.com/pkg/errors"
)
// OpenAPI2Validator returns request and response validators that
// can drop into an nvelope-based http handler chain. The first
// returned function should be placed just before or after the request
// decoder. The second function should be as the parameter for
// nvelope.WithAPIEnforcer().
//
// OpenAPI2Validator's parameters are the filename where the JSON or
// YAML swagger can be found and an option specifier for openapi3filter:
// should it return MultiError or just a single error.
func OpenAPI2Validator(
swaggerFile string,
multiError bool,
) (
func(r *http.Request, body nvelope.Body) nject.TerminalError,
nvelope.APIEnforcerFunc,
error,
) {
input, err := ioutil.ReadFile(swaggerFile)
if err != nil {
return nil, nil, errors.Wrapf(err, "read %s", swaggerFile)
}
var v2Doc openapi2.T
switch strings.ToLower(filepath.Ext(swaggerFile)) {
case "json":
err = json.Unmarshal(input, &v2Doc)
case "yml", "yaml":
err = yaml.Unmarshal(input, &v2Doc)
default:
return nil, nil, errors.Errorf("Cannot determine (based on extension) if %s is YAML or JSON", swaggerFile)
}
if err != nil {
return nil, nil, errors.Wrapf(err, "unmarshal %s", swaggerFile)
}
v3Doc, err := openapi2conv.ToV3(&v2Doc)
if err != nil {
return nil, nil, errors.Wrapf(err, "convert %s to OpenAPI v3", swaggerFile)
}
return OpenAPI3ValidatorFromParsed(v3Doc, swaggerFile, multiError)
}