servicechecker/pkg/swaggerset/swaggerset.go

83 lines
1.9 KiB
Go
Raw Normal View History

package swaggerset
import (
"errors"
"net/http"
"sync"
openapi "go.unistack.org/micro-proto/v4/openapiv3"
)
var errNotFound = errors.New("file descriptor not found")
type SwaggerSet struct {
mu sync.Mutex
files map[string]*openapi.Document
}
func NewSwaggerSet() *SwaggerSet {
return &SwaggerSet{
mu: sync.Mutex{},
files: make(map[string]*openapi.Document, 0),
}
}
func (p *SwaggerSet) GetMessage(addr, svc, mth string) (*Message, error) {
if svc == "" || mth == "" || addr == "" {
return nil, errors.New("addr or service name is empty")
}
p.mu.Lock()
doc := p.files[addr+"|"+svc]
p.mu.Unlock()
var reqParam, reqBody, rsp interface{}
var typeReq string
for _, path := range doc.Paths.GetPath() {
if path.GetName() == mth {
if path.GetValue().GetGet() != nil {
typeReq = http.MethodGet
reqParam, reqBody, rsp = handleOperation(path.GetValue().GetGet(), doc)
}
if path.GetValue().GetPost() != nil {
typeReq = http.MethodPost
reqParam, reqBody, rsp = handleOperation(path.GetValue().GetPost(), doc)
}
if path.GetValue().GetDelete() != nil {
typeReq = http.MethodDelete
reqParam, reqBody, rsp = handleOperation(path.GetValue().GetDelete(), doc)
}
if path.GetValue().GetPatch() != nil {
typeReq = http.MethodPatch
reqParam, reqBody, rsp = handleOperation(path.GetValue().GetPatch(), doc)
}
if path.GetValue().GetPut() != nil {
typeReq = http.MethodPut
reqParam, reqBody, rsp = handleOperation(path.GetValue().GetPut(), doc)
}
}
}
msg := &Message{
Type: typeReq,
Request: httpRequest{
Header: reqParam,
Body: reqBody,
},
Response: rsp,
}
return msg, nil
}
func (p *SwaggerSet) AddSwaggerset(addr, svc string, data []byte) error {
doc, err := openapi.ParseDocument(data)
if err != nil {
return err
}
p.mu.Lock()
p.files[addr+"|"+svc] = doc
p.mu.Unlock()
return nil
}