servicechecker/pkg/swaggerset/swaggerset.go
Кирилл Горбунов 7a302ce899 #2 - add swaggerset (#8)
Co-authored-by: Gorbunov Kirill Andreevich <kgorbunov@mtsbank.ru>
Reviewed-on: #8
Reviewed-by: Василий Толстов <v.tolstov@unistack.org>
Co-authored-by: Кирилл Горбунов <kirya_gorbunov_2015@mail.ru>
Co-committed-by: Кирилл Горбунов <kirya_gorbunov_2015@mail.ru>
2024-12-06 19:01:07 +03:00

83 lines
1.9 KiB
Go

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
}