gitee.com/gricks/utils@v1.0.8/dingtalk.go (about)

     1  package utils
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net"
     8  	"net/http"
     9  	"time"
    10  )
    11  
    12  var (
    13  	dingtalkURL      = "https://oapi.dingtalk.com/robot/send?access_token="
    14  	dingtalkBodyType = "application/json;charset=UTF-8"
    15  	dingtalkTextType = "markdown"
    16  	dingtalkDialer   = &http.Client{
    17  		Transport: &http.Transport{
    18  			Proxy: http.ProxyFromEnvironment,
    19  			DialContext: (&net.Dialer{
    20  				Timeout:   30 * time.Second,
    21  				KeepAlive: 30 * time.Second,
    22  				DualStack: true,
    23  			}).DialContext,
    24  			MaxIdleConns:          100,
    25  			IdleConnTimeout:       90 * time.Second,
    26  			TLSHandshakeTimeout:   10 * time.Second,
    27  			ExpectContinueTimeout: 1 * time.Second,
    28  		},
    29  		Timeout: 10 * time.Second,
    30  	}
    31  )
    32  
    33  type dingtalkContext struct {
    34  	MsgType  string `json:"msgtype"`
    35  	Markdown struct {
    36  		Title string `json:"title"`
    37  		Text  string `json:"text"`
    38  	} `json:"markdown"`
    39  }
    40  
    41  type Dingtalk struct {
    42  	token string
    43  }
    44  
    45  func NewDingtalk(token string) *Dingtalk {
    46  	return &Dingtalk{token: token}
    47  }
    48  
    49  func (d *Dingtalk) Send(title string, text string) error {
    50  	data := &dingtalkContext{}
    51  	data.MsgType = dingtalkTextType
    52  	data.Markdown.Title = title
    53  	data.Markdown.Text = text
    54  
    55  	dataByte, err := json.Marshal(data)
    56  	if err != nil {
    57  		return err
    58  	}
    59  
    60  	rsp, err := dingtalkDialer.Post(dingtalkURL+d.token, dingtalkBodyType, bytes.NewReader(dataByte))
    61  	if err != nil {
    62  		return err
    63  	}
    64  	defer rsp.Body.Close()
    65  
    66  	if rsp.StatusCode != http.StatusOK {
    67  		return fmt.Errorf("Dingtalk unexpected response, code %d", rsp.StatusCode)
    68  	}
    69  	return nil
    70  }