github.com/shuguocloud/go-zero@v1.3.0/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/shuguocloud/go-zero/core/logx" 11 ) 12 13 const httpTimeout = time.Second * 5 14 15 // ErrWriteFailed is an error that indicates failed to submit a StatReport. 16 var ErrWriteFailed = errors.New("submit failed") 17 18 // A RemoteWriter is a writer to write StatReport. 19 type RemoteWriter struct { 20 endpoint string 21 } 22 23 // NewRemoteWriter returns a RemoteWriter. 24 func NewRemoteWriter(endpoint string) Writer { 25 return &RemoteWriter{ 26 endpoint: endpoint, 27 } 28 } 29 30 func (rw *RemoteWriter) Write(report *StatReport) error { 31 bs, err := json.Marshal(report) 32 if err != nil { 33 return err 34 } 35 36 client := &http.Client{ 37 Timeout: httpTimeout, 38 } 39 resp, err := client.Post(rw.endpoint, "application/json", bytes.NewBuffer(bs)) 40 if err != nil { 41 return err 42 } 43 defer resp.Body.Close() 44 45 if resp.StatusCode != http.StatusOK { 46 logx.Errorf("write report failed, code: %d, reason: %s", resp.StatusCode, resp.Status) 47 return ErrWriteFailed 48 } 49 50 return nil 51 }