util.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package internal
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "encoding/json"
  7. "errors"
  8. "io/ioutil"
  9. "net/http"
  10. "time"
  11. )
  12. // GetTLSConfig generate tls.Config from CAFile
  13. func GetTLSConfig(CAFile string) (*tls.Config, error) {
  14. caCert, err := ioutil.ReadFile(CAFile)
  15. if err != nil {
  16. return nil, err
  17. }
  18. caCertPool := x509.NewCertPool()
  19. if ok := caCertPool.AppendCertsFromPEM(caCert); !ok {
  20. return nil, errors.New("Failed to add CA to pool")
  21. }
  22. tlsConfig := &tls.Config{
  23. RootCAs: caCertPool,
  24. }
  25. tlsConfig.BuildNameToCertificate()
  26. return tlsConfig, nil
  27. }
  28. // CreateHTTPClient returns a http.Client
  29. func CreateHTTPClient(CAFile string) (*http.Client, error) {
  30. var tlsConfig *tls.Config
  31. var err error
  32. if CAFile != "" {
  33. tlsConfig, err = GetTLSConfig(CAFile)
  34. if err != nil {
  35. return nil, err
  36. }
  37. }
  38. tr := &http.Transport{
  39. MaxIdleConnsPerHost: 20,
  40. TLSClientConfig: tlsConfig,
  41. }
  42. return &http.Client{
  43. Transport: tr,
  44. Timeout: 5 * time.Second,
  45. }, nil
  46. }
  47. // PostJSON posts json object to url
  48. func PostJSON(url string, obj interface{}, client *http.Client) (*http.Response, error) {
  49. if client == nil {
  50. client, _ = CreateHTTPClient("")
  51. }
  52. b := new(bytes.Buffer)
  53. if err := json.NewEncoder(b).Encode(obj); err != nil {
  54. return nil, err
  55. }
  56. return client.Post(url, "application/json; charset=utf-8", b)
  57. }
  58. // GetJSON gets a json response from url
  59. func GetJSON(url string, obj interface{}, client *http.Client) (*http.Response, error) {
  60. if client == nil {
  61. client, _ = CreateHTTPClient("")
  62. }
  63. resp, err := client.Get(url)
  64. if err != nil {
  65. return resp, err
  66. }
  67. if resp.StatusCode != http.StatusOK {
  68. return resp, errors.New("HTTP status code is not 200")
  69. }
  70. defer resp.Body.Close()
  71. body, err := ioutil.ReadAll(resp.Body)
  72. if err != nil {
  73. return resp, err
  74. }
  75. return resp, json.Unmarshal(body, obj)
  76. }