github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/quality/elastic_search_transport.go (about)

     1  /*
     2   * Copyright (C) 2019 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package quality
    19  
    20  import (
    21  	"io"
    22  	"strings"
    23  	"time"
    24  
    25  	"github.com/mysteriumnetwork/node/requests"
    26  	"github.com/pkg/errors"
    27  )
    28  
    29  // NewElasticSearchTransport creates transport allowing to send events to ElasticSearch through HTTP
    30  func NewElasticSearchTransport(httpClient *requests.HTTPClient, url string, timeout time.Duration) Transport {
    31  	return &elasticSearchTransport{
    32  		httpClient: httpClient,
    33  		url:        url,
    34  	}
    35  }
    36  
    37  type elasticSearchTransport struct {
    38  	httpClient *requests.HTTPClient
    39  	url        string
    40  }
    41  
    42  func (transport *elasticSearchTransport) SendEvent(event Event) error {
    43  	req, err := requests.NewPostRequest(transport.url, "/", event)
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	response, err := transport.httpClient.Do(req)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	defer response.Body.Close()
    53  
    54  	bodyBytes, err := io.ReadAll(response.Body)
    55  	if err != nil {
    56  		return errors.Wrapf(err, "error while reading response body")
    57  	}
    58  	body := string(bodyBytes)
    59  
    60  	if response.StatusCode != 200 {
    61  		return errors.Errorf("unexpected response status: %v, body: %v", response.Status, body)
    62  	}
    63  
    64  	if strings.ToUpper(body) != "OK" {
    65  		return errors.Errorf("unexpected response body: %v", body)
    66  	}
    67  
    68  	return nil
    69  }