github.com/lingyao2333/mo-zero@v1.4.1/core/stat/remotewriter.go (about)

     1  package stat
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"errors"
     7  	"net/http"
     8  	"time"
     9  
    10  	"github.com/lingyao2333/mo-zero/core/logx"
    11  )
    12  
    13  const (
    14  	httpTimeout     = time.Second * 5
    15  	jsonContentType = "application/json; charset=utf-8"
    16  )
    17  
    18  // ErrWriteFailed is an error that indicates failed to submit a StatReport.
    19  var ErrWriteFailed = errors.New("submit failed")
    20  
    21  // A RemoteWriter is a writer to write StatReport.
    22  type RemoteWriter struct {
    23  	endpoint string
    24  }
    25  
    26  // NewRemoteWriter returns a RemoteWriter.
    27  func NewRemoteWriter(endpoint string) Writer {
    28  	return &RemoteWriter{
    29  		endpoint: endpoint,
    30  	}
    31  }
    32  
    33  func (rw *RemoteWriter) Write(report *StatReport) error {
    34  	bs, err := json.Marshal(report)
    35  	if err != nil {
    36  		return err
    37  	}
    38  
    39  	client := &http.Client{
    40  		Timeout: httpTimeout,
    41  	}
    42  	resp, err := client.Post(rw.endpoint, jsonContentType, bytes.NewReader(bs))
    43  	if err != nil {
    44  		return err
    45  	}
    46  	defer resp.Body.Close()
    47  
    48  	if resp.StatusCode != http.StatusOK {
    49  		logx.Errorf("write report failed, code: %d, reason: %s", resp.StatusCode, resp.Status)
    50  		return ErrWriteFailed
    51  	}
    52  
    53  	return nil
    54  }