100 lines
2.3 KiB
Go
100 lines
2.3 KiB
Go
package sequence_client
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/valyala/fasthttp"
|
|
"strings"
|
|
)
|
|
|
|
type RequestData struct {
|
|
Type string `json:"type"`
|
|
Limit string `json:"limit"`
|
|
}
|
|
|
|
type ResponseStatus struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
type Response struct {
|
|
Status ResponseStatus `json:"status"`
|
|
Data json.RawMessage `json:"data"`
|
|
}
|
|
|
|
type Client struct {
|
|
BaseURL string
|
|
XApiKey string
|
|
HTTPClient *fasthttp.Client
|
|
}
|
|
|
|
func NewClient(baseURL, xApiKey string) *Client {
|
|
return &Client{
|
|
BaseURL: baseURL,
|
|
XApiKey: xApiKey,
|
|
HTTPClient: &fasthttp.Client{},
|
|
}
|
|
}
|
|
|
|
func (c *Client) GetSequence(requestData RequestData, action string) (interface{}, error) {
|
|
var url string
|
|
requestBody, err := json.Marshal(requestData)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to marshal request data: %w", err)
|
|
}
|
|
|
|
for {
|
|
if strings.ToUpper(action) == "INC" {
|
|
url = fmt.Sprintf("%s/v1/sequence/inc", c.BaseURL)
|
|
break
|
|
}
|
|
if strings.ToUpper(action) == "SKIP" {
|
|
url = fmt.Sprintf("%s/v1/sequence/skip", c.BaseURL)
|
|
break
|
|
}
|
|
return nil, fmt.Errorf("invalid action")
|
|
}
|
|
|
|
req := fasthttp.AcquireRequest()
|
|
defer fasthttp.ReleaseRequest(req)
|
|
|
|
req.SetRequestURI(url)
|
|
req.Header.SetMethod("PUT")
|
|
req.Header.SetContentType("application/json")
|
|
req.Header.Set("x-api-key", c.XApiKey)
|
|
req.SetBody(requestBody)
|
|
|
|
resp := fasthttp.AcquireResponse()
|
|
defer fasthttp.ReleaseResponse(resp)
|
|
|
|
if err := c.HTTPClient.Do(req, resp); err != nil {
|
|
return nil, fmt.Errorf("request failed: %w", err)
|
|
}
|
|
|
|
if resp.StatusCode() != fasthttp.StatusOK {
|
|
return nil, fmt.Errorf("server returned status %d: %s", resp.StatusCode(), string(resp.Body()))
|
|
}
|
|
|
|
var response Response
|
|
if err := json.Unmarshal(resp.Body(), &response); err != nil {
|
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
|
}
|
|
|
|
if response.Status.Code != 0 {
|
|
return nil, fmt.Errorf("server returned error: %s", response.Status.Message)
|
|
}
|
|
var dataAsSlice []string
|
|
if err := json.Unmarshal(response.Data, &dataAsSlice); err == nil {
|
|
return dataAsSlice, nil
|
|
}
|
|
|
|
var dataAsMap map[string]string
|
|
if err := json.Unmarshal(response.Data, &dataAsMap); err == nil {
|
|
return dataAsMap, nil
|
|
}
|
|
|
|
return nil, errors.New("unexpected data format in response")
|
|
|
|
}
|