Files
wahrwelt-a-d-setup/components/neo/internal/server/exploits/farm.go
T

67 lines
1.7 KiB
Go

package exploits
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/c4t-but-s4d/neo/v2/internal/server/config"
)
func NewFarmClient(cfg config.FarmConfig) *FarmClient {
return &FarmClient{
url: strings.TrimRight(cfg.URL, "/"),
password: cfg.Password,
client: http.Client{
Timeout: 3 * time.Second,
},
}
}
type FarmClient struct {
url string
password string
client http.Client
}
const maxFarmConfigBytes = 1 << 20
func (fc *FarmClient) FillConfig(ctx context.Context, cfg *config.FarmConfig) error {
url := fmt.Sprintf("%s/api/get_config", fc.url)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return fmt.Errorf("создание запроса к Farm: %w", err)
}
req.Header.Set("Authorization", fc.password)
req.Header.Set("X-Token", fc.password)
resp, err := fc.client.Do(req)
if err != nil {
return fmt.Errorf("выполнение запроса к Farm: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
logrus.Errorf("Не удалось закрыть ответ Farm: %v", err)
}
}()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Farm вернул HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxFarmConfigBytes+1))
if err != nil {
return fmt.Errorf("чтение конфигурации Farm: %w", err)
}
if len(body) > maxFarmConfigBytes {
return fmt.Errorf("конфигурация Farm превышает %d байт", maxFarmConfigBytes)
}
if err := cfg.ParseJSON(bytes.NewReader(body)); err != nil {
return fmt.Errorf("разбор ответа Farm: %w", err)
}
return nil
}