-
Notifications
You must be signed in to change notification settings - Fork 108
/
server.go
85 lines (68 loc) · 2.04 KB
/
server.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
// SPDX-License-Identifier: MIT
package openapi
import (
"strings"
"github.com/caixw/apidoc/v7/core"
"github.com/caixw/apidoc/v7/internal/ast"
"github.com/caixw/apidoc/v7/internal/locale"
)
// 去掉 URL 中的 {} 模板参数。使其符合 is.URL 的判断规则
var urlreplace = strings.NewReplacer("{", "", "}", "")
// Server 服务器描述信息
type Server struct {
URL string `json:"url" yaml:"url"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
Variables map[string]*ServerVariable `json:"variables,omitempty" yaml:"variables,omitempty"`
}
// ServerVariable Server 中 URL 模板中对应的参数变量值
type ServerVariable struct {
Enum []string `json:"enum,omitempty" yaml:"enum,omitempty"`
Default string `json:"default" yaml:"default"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
}
func newServer(srv *ast.Server) *Server {
desc := srv.Summary.V()
if srv.Description != nil && srv.Description.Text != nil {
desc = srv.Description.V()
}
return &Server{
URL: srv.URL.V(),
Description: desc,
}
}
func (srv *Server) sanitize() *core.Error {
url := urlreplace.Replace(srv.URL)
if url == "" { // 可以是 / 未必是一个 URL
return core.NewError(locale.ErrIsEmpty, "url").WithField("url")
}
for key, val := range srv.Variables {
if err := val.sanitize(); err != nil {
err.Field = "variables[" + key + "]." + err.Field
return err
}
k := "{" + key + "}"
if strings.Index(srv.URL, k) < 0 {
return core.NewError(locale.ErrInvalidValue).WithField("variables[" + key + "]")
}
}
return nil
}
func (v *ServerVariable) sanitize() *core.Error {
if v.Default == "" {
return core.NewError(locale.ErrIsEmpty, "default").WithField("default")
}
if len(v.Enum) == 0 {
return nil
}
found := false
for _, item := range v.Enum {
if item == v.Default {
found = true
break
}
}
if !found {
return core.NewError(locale.ErrInvalidValue).WithField("default")
}
return nil
}