forked from parvez3019/go-swagger3
/
parser.go
68 lines (59 loc) · 2.04 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
package operations
import (
"go/ast"
"strings"
. "github.com/Arlet2/go-swagger3/openApi3Schema"
"github.com/Arlet2/go-swagger3/parser/model"
"github.com/Arlet2/go-swagger3/parser/schema"
)
type Parser interface {
Parse(pkgPath, pkgName string, astComments []*ast.Comment) error
}
type parser struct {
OpenAPI *OpenAPIObject
model.Utils
schema.Parser
}
func NewParser(utils model.Utils, api *OpenAPIObject, schemaParser schema.Parser) Parser {
return &parser{
Utils: utils,
OpenAPI: api,
Parser: schemaParser,
}
}
func (p *parser) Parse(pkgPath, pkgName string, astComments []*ast.Comment) error {
operation := &OperationObject{Responses: map[string]*ResponseObject{}}
if !strings.HasPrefix(pkgPath, p.ModulePath) || (p.HandlerPath != "" && !strings.HasPrefix(pkgPath, p.HandlerPath)) {
return nil
}
for _, astComment := range astComments {
comment := strings.TrimSpace(strings.TrimLeft(astComment.Text, "/"))
if len(comment) == 0 {
continue
}
if err := p.parseOperationFromComment(pkgPath, pkgName, comment, operation); err != nil {
return err
}
}
return nil
}
func (p *parser) parseOperationFromComment(pkgPath string, pkgName string, comment string, operation *OperationObject) error {
attribute := strings.Fields(comment)[0]
switch strings.ToLower(attribute) {
case "@title":
operation.Summary = strings.TrimSpace(comment[len(attribute):])
case "@description":
operation.Description = strings.Join([]string{operation.Description, strings.TrimSpace(comment[len(attribute):])}, " ")
case "@param":
return p.parseParamComment(pkgPath, pkgName, operation, strings.TrimSpace(comment[len(attribute):]))
case "@header":
return p.parseHeaders(pkgPath, pkgName, operation, strings.TrimSpace(comment[len(attribute):]))
case "@success", "@failure":
return p.parseResponseComment(pkgPath, pkgName, operation, strings.TrimSpace(comment[len(attribute):]))
case "@resource", "@tag":
p.parseResourceAndTag(comment, attribute, operation)
case "@route", "@router":
return p.parseRouteComment(operation, comment)
}
return nil
}