forked from kyma-project/kyma
/
specification_service.go
119 lines (96 loc) · 2.41 KB
/
specification_service.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package assetstore
import (
"io/ioutil"
"net/http"
"crypto/tls"
"fmt"
"strings"
"github.com/kyma-project/kyma/components/console-backend-service/internal/domain/assetstore/spec"
)
//go:generate mockery -name=specificationSvc -output=automock -outpkg=automock -case=underscore
//go:generate failery -name=specificationSvc -case=underscore -output disabled -outpkg disabled
type specificationSvc interface {
AsyncAPI(baseURL, name string) (*spec.AsyncAPISpec, error)
}
type specificationService struct {
cfg Config
endpoint string
client *http.Client
}
func newSpecificationService(cfg Config) (*specificationService, error) {
client := &http.Client{}
if !cfg.VerifySSL {
transCfg := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore invalid SSL certificates
}
client.Transport = transCfg
}
protocol := "http"
if cfg.Secure {
protocol = protocol + "s"
}
endpoint := fmt.Sprintf("%s://%s", protocol, cfg.Address)
return &specificationService{
cfg: cfg,
endpoint: endpoint,
client: client,
}, nil
}
func (s *specificationService) AsyncAPI(baseURL, name string) (*spec.AsyncAPISpec, error) {
data, err := s.readData(baseURL, name)
if err != nil || len(data) == 0 {
return nil, err
}
asyncApiSpec := new(spec.AsyncAPISpec)
err = asyncApiSpec.Decode(data)
if err != nil {
return nil, err
}
return asyncApiSpec, nil
}
func (s *specificationService) readData(baseURL, name string) ([]byte, error) {
path := s.preparePath(baseURL, name)
if path == "" {
return nil, nil
}
data, err := s.fetch(path)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, nil
}
return data, nil
}
func (s *specificationService) preparePath(baseURL, name string) string {
if baseURL == "" || name == "" {
return ""
}
splitedBaseURL := strings.Split(baseURL, "/")
if len(splitedBaseURL) < 3 {
return ""
}
bucketName := splitedBaseURL[len(splitedBaseURL)-2]
assetName := splitedBaseURL[len(splitedBaseURL)-1]
return fmt.Sprintf("%s/%s/%s/%s", s.endpoint, bucketName, assetName, name)
}
func (s *specificationService) fetch(path string) ([]byte, error) {
if path == "" {
return nil, nil
}
resp, err := s.client.Get(path)
if err != nil {
return nil, err
}
defer func() {
err = resp.Body.Close()
}()
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}