utils.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "reflect"
  10. )
  11. /**
  12. Params:
  13. argUrl: reqeust url
  14. argReq: reqeust contents
  15. argType: reqeust type
  16. argHead: reqeust head
  17. Retrun: reqesut result body
  18. */
  19. func SendHttpRequest(argUrl string, argReq string, argType string, argHead map[string]string) ([]byte, error) {
  20. fmt.Print(">============<\n")
  21. fmt.Printf("[request url]:%v\n", argUrl)
  22. fmt.Printf("[request content]:%v\n", argReq)
  23. fmt.Printf("[request type]:%v\n", argType)
  24. fmt.Printf("[request head]:%+v\n", argHead)
  25. //*/
  26. bReq := []byte(argReq)
  27. req, err := http.NewRequest(argType, argUrl, bytes.NewBuffer(bReq))
  28. if err != nil {
  29. return nil, err
  30. }
  31. for key, vaule := range argHead {
  32. req.Header.Set(key, vaule)
  33. }
  34. tr := &http.Transport{
  35. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  36. }
  37. client := &http.Client{Transport: tr}
  38. resp, err := client.Do(req)
  39. if err != nil {
  40. return nil, err
  41. }
  42. defer resp.Body.Close()
  43. body, _ := ioutil.ReadAll(resp.Body)
  44. fmt.Printf("[respons body]:%v\n", string(body))
  45. return body, nil
  46. }
  47. /**
  48. check the https response code
  49. */
  50. func CheckHttpsCode(resp interface{}) error {
  51. res := reflect.ValueOf(resp)
  52. // struct
  53. if res.Kind() == reflect.Struct {
  54. // exported field
  55. f := res.FieldByName("Code")
  56. if f.IsValid() {
  57. if f.Interface() == 0 {
  58. return nil
  59. } else {
  60. msg := res.FieldByName("Message")
  61. err := errors.New(msg.Interface().(string))
  62. return err
  63. }
  64. }
  65. }
  66. return errors.New("response format error")
  67. }