1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. "net/http"
    6. "io/ioutil"
    7. "strings"
    8. "time"
    9. )
    10. func main() {
    11. sendMsg("hehe")
    12. }
    13. const httpTimeoutSecond = time.Duration(30) * time.Second
    14. type message string
    15. type Response struct {
    16. ErrMsg string `json:"errmsg"`
    17. ErrCode int64 `json:"errcode"`
    18. }
    19. func sendMsg(message) (*Response, error){
    20. res := &Response{}
    21. pushURL := "https://oapi.dingtalk.com/robot/send?access_token=068bb8f58f178d2e517c4b6d078796f9cb0466412641f0a0cbd952bbb754b4bd"
    22. req, err := http.NewRequest(http.MethodPost,pushURL,strings.NewReader(`{"msgtype": "text","text": {"content": "starkwang"}}`))
    23. if err != nil {
    24. fmt.Println("01")
    25. }
    26. req.Header.Add("Accept-Charset","utf8")
    27. req.Header.Add("Content-Type","application/json")
    28. client := new(http.Client)
    29. client.Timeout = httpTimeoutSecond
    30. fmt.Println(req)
    31. resp ,err := client.Do(req)
    32. fmt.Println(resp)
    33. if err != nil {
    34. fmt.Println("02")
    35. }
    36. defer resp.Body.Close()
    37. resultByte, err := ioutil.ReadAll(resp.Body)
    38. if err != nil {
    39. fmt.Println("03")
    40. }
    41. err = json.Unmarshal(resultByte, &res)
    42. if err != nil {
    43. fmt.Errorf("unmarshal http response body from json error = %v", err)
    44. }
    45. if res.ErrCode != 0 {
    46. return res, fmt.Errorf("send message to dingtalk error = %s", res.ErrMsg)
    47. }
    48. fmt.Println("res----",res)
    49. return res, nil
    50. }