github.com/songzhibin97/gkit@v1.2.13/watching/reporter.go (about)

     1  package watching
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"mime/multipart"
     9  	"net/http"
    10  )
    11  
    12  type ProfileReporter interface {
    13  	Report(pType string, buf []byte, reason string, eventID string) error
    14  }
    15  
    16  type HttpReporter struct {
    17  	token string
    18  	url   string
    19  }
    20  
    21  type Response struct {
    22  	Code    int    `json:"code"`
    23  	Message string `json:"message"`
    24  }
    25  
    26  func NewReporter(token string, url string) ProfileReporter {
    27  	return &HttpReporter{
    28  		token: token,
    29  		url:   url,
    30  	}
    31  }
    32  
    33  func (r *HttpReporter) Report(ptype string, buf []byte, reason string, eventID string) error {
    34  	body := &bytes.Buffer{}
    35  	writer := multipart.NewWriter(body)
    36  	part, err := writer.CreateFormFile("profile", "go-pprof-profile")
    37  	if err != nil {
    38  		return fmt.Errorf("create form File err: %v", err)
    39  	}
    40  	if _, err := part.Write(buf); err != nil {
    41  		return fmt.Errorf("write buf to file part err: %v", err)
    42  	}
    43  	writer.WriteField("token", r.token)      // nolint: errcheck
    44  	writer.WriteField("profile_type", ptype) // nolint: errcheck
    45  	writer.WriteField("event_id", eventID)   // nolint: errcheck
    46  	writer.WriteField("comment", reason)     // nolint: errcheck
    47  	writer.Close()                           // nolint: errcheck
    48  	request, err := http.NewRequest("POST", r.url, body)
    49  	if err != nil {
    50  		return fmt.Errorf("NewRequest err: %v", err)
    51  	}
    52  
    53  	request.Header.Add("Content-Type", writer.FormDataContentType())
    54  	client := &http.Client{}
    55  	response, err := client.Do(request)
    56  	if err != nil {
    57  		return fmt.Errorf("do Request err: %v", err)
    58  	}
    59  	defer response.Body.Close() // nolint: errcheck
    60  
    61  	respContent, err := ioutil.ReadAll(response.Body)
    62  	if err != nil {
    63  		return fmt.Errorf("read response err: %v", err)
    64  	}
    65  
    66  	rsp := &Response{}
    67  	if err := json.Unmarshal(respContent, rsp); err != nil {
    68  		return fmt.Errorf("failed to decode resp json: %v", err)
    69  	}
    70  
    71  	if rsp.Code != 1 {
    72  		return fmt.Errorf("code: %d, msg: %s", rsp.Code, rsp.Message)
    73  	}
    74  	return nil
    75  }