smtpbiz-exporter/internal/client/smtp.go
2024-12-03 01:47:04 +03:00

60 lines
1.3 KiB
Go

package client
import (
"encoding/json"
"fmt"
"github.com/gofiber/fiber/v2"
"strings"
)
type Client interface {
UseMethod(method string, endpoint string, params map[string]interface{}) ([]byte, error)
}
type SMTPClient struct {
apiURL string
client *fiber.Client
apiKey string
}
func NewSMTPClient(apiURL, apiKey string) *SMTPClient {
return &SMTPClient{
apiURL: apiURL,
client: fiber.AcquireClient(),
apiKey: apiKey,
}
}
func (c *SMTPClient) UseMethod(method string, endpoint string, params map[string]interface{}) ([]byte, error) {
url := fmt.Sprintf("%s/%s", c.apiURL, endpoint)
var req *fiber.Agent
switch strings.ToUpper(method) {
case fiber.MethodGet:
// todo get params
req = c.client.Get(url)
case fiber.MethodPost:
request, err := json.Marshal(params)
if err != nil {
return nil, fmt.Errorf("failed marshal params: %w", err)
}
req = c.client.Post(url)
req.Set("Content-Type", "application/json").Body(request)
default:
return nil, fmt.Errorf("unsupported HTTP method: %s", method)
}
req.Set("Authorization", c.apiKey)
statusCode, respBody, errs := req.Bytes()
if errs != nil {
return nil, fmt.Errorf("request errors: %v", errs)
}
if statusCode != fiber.StatusOK {
return nil, fmt.Errorf("failed with status code %d: %s", statusCode, string(respBody))
}
return respBody, nil
}