utils.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package smsdriver
  15. import (
  16. "bytes"
  17. "context"
  18. "io/ioutil"
  19. "net/http"
  20. "net/url"
  21. "strings"
  22. "yunion.io/x/jsonutils"
  23. "yunion.io/x/pkg/errors"
  24. utilerr "yunion.io/x/pkg/errors"
  25. "yunion.io/x/pkg/gotypes"
  26. "yunion.io/x/pkg/util/httputils"
  27. )
  28. const (
  29. LARK_MESSAGE_SUCCESS = "success"
  30. )
  31. var (
  32. cli = &http.Client{
  33. Transport: httputils.GetTransport(true),
  34. }
  35. ctx = context.Background()
  36. )
  37. // 通知请求
  38. func sendRequest(url string, method httputils.THttpMethod, header http.Header, params url.Values, body jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  39. var bodystr string
  40. if !gotypes.IsNil(body) {
  41. bodystr = body.String()
  42. }
  43. jbody := strings.NewReader(bodystr)
  44. if header == nil {
  45. header = http.Header{}
  46. }
  47. if header == nil {
  48. header = http.Header{}
  49. }
  50. if len(header.Values("Content-Type")) == 0 {
  51. header.Set("Content-Type", "application/json")
  52. }
  53. if params != nil {
  54. url += params.Encode()
  55. }
  56. resp, err := httputils.Request(cli, ctx, method, url, header, jbody, true)
  57. if err != nil {
  58. return nil, utilerr.Wrap(err, "http request")
  59. }
  60. rbody, err := ioutil.ReadAll(resp.Body)
  61. if err != nil {
  62. return nil, err
  63. }
  64. rbody = bytes.TrimSpace(rbody)
  65. var jrbody jsonutils.JSONObject = nil
  66. if len(rbody) > 0 && (rbody[0] == '{' || rbody[0] == '[') {
  67. jrbody, _ = jsonutils.Parse(rbody)
  68. } else {
  69. return nil, errors.Wrap(err, "resource not json")
  70. }
  71. return jrbody, nil
  72. }