This repository has been archived by the owner on Jan 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 115
/
parser.go
86 lines (68 loc) · 1.82 KB
/
parser.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Package parser is an API blueprint parser and renderer
package parser
import (
"bytes"
"io"
"github.com/bukalapak/snowboard/api"
)
type Parser interface {
Parse(r io.Reader) ([]byte, error)
Validate(r io.Reader) ([]byte, error)
Version() string
}
// Parse formats API blueprint as blueprint.API struct using selected Parser
func Parse(r io.Reader, engine Parser) (*api.API, error) {
el, err := parseElement(r, engine)
if err != nil {
return nil, err
}
return api.NewAPI(el)
}
// ParseAsJSON parse API blueprint as API Element JSON
func ParseAsJSON(r io.Reader, engine Parser) ([]byte, error) {
return engine.Parse(r)
}
// Validate validates API blueprint using selected Parser
func Validate(r io.Reader, engine Parser) (*api.API, error) {
el, err := validateElement(r, engine)
if err == nil && el.Object() == nil {
return nil, nil
}
if err != nil {
return nil, err
}
return api.NewAPI(el)
}
// Load reads API blueprint from file as blueprint.API struct using selected Parser
func Load(name string, engine Parser) (*api.API, error) {
b, err := Read(name)
if err != nil {
return nil, err
}
return Parse(bytes.NewReader(b), engine)
}
// LoadAsJSON reads API blueprint from file as API Element JSON using selected Parser
func LoadAsJSON(name string, engine Parser) ([]byte, error) {
b, err := Read(name)
if err != nil {
return nil, err
}
return ParseAsJSON(bytes.NewReader(b), engine)
}
func parseElement(r io.Reader, engine Parser) (*api.Element, error) {
b, err := ParseAsJSON(r, engine)
if err != nil {
return nil, err
}
return api.ParseJSON(bytes.NewReader(b))
}
func validateElement(r io.Reader, engine Parser) (*api.Element, error) {
b, err := engine.Validate(r)
if err != nil {
return nil, err
}
if len(b) == 0 {
return &api.Element{}, nil
}
return api.ParseJSON(bytes.NewReader(b))
}