You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
1.9 KiB

  1. package util
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. )
  10. var (
  11. client *http.Client
  12. Transport *http.Transport
  13. )
  14. func init() {
  15. Transport = &http.Transport{
  16. MaxIdleConnsPerHost: 1024,
  17. }
  18. client = &http.Client{Transport: Transport}
  19. }
  20. func PostBytes(url string, body []byte) ([]byte, error) {
  21. r, err := client.Post(url, "application/octet-stream", bytes.NewReader(body))
  22. if err != nil {
  23. return nil, err
  24. }
  25. defer r.Body.Close()
  26. b, err := ioutil.ReadAll(r.Body)
  27. if err != nil {
  28. return nil, err
  29. }
  30. return b, nil
  31. }
  32. func Post(url string, values url.Values) ([]byte, error) {
  33. r, err := client.PostForm(url, values)
  34. if err != nil {
  35. return nil, err
  36. }
  37. defer r.Body.Close()
  38. b, err := ioutil.ReadAll(r.Body)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return b, nil
  43. }
  44. func Get(url string) ([]byte, error) {
  45. r, err := client.Get(url)
  46. if err != nil {
  47. return nil, err
  48. }
  49. defer r.Body.Close()
  50. b, err := ioutil.ReadAll(r.Body)
  51. if r.StatusCode != 200 {
  52. return nil, fmt.Errorf("%s: %s", url, r.Status)
  53. }
  54. if err != nil {
  55. return nil, err
  56. }
  57. return b, nil
  58. }
  59. func Delete(url string) error {
  60. req, err := http.NewRequest("DELETE", url, nil)
  61. if err != nil {
  62. return err
  63. }
  64. resp, e := client.Do(req)
  65. if e != nil {
  66. return e
  67. }
  68. defer resp.Body.Close()
  69. if _, err := ioutil.ReadAll(resp.Body); err != nil {
  70. return err
  71. }
  72. return nil
  73. }
  74. func DownloadUrl(fileUrl string) (filename string, content []byte, e error) {
  75. response, err := client.Get(fileUrl)
  76. if err != nil {
  77. return "", nil, err
  78. }
  79. defer response.Body.Close()
  80. contentDisposition := response.Header["Content-Disposition"]
  81. if len(contentDisposition) > 0 {
  82. if strings.HasPrefix(contentDisposition[0], "filename=") {
  83. filename = contentDisposition[0][len("filename="):]
  84. filename = strings.Trim(filename, "\"")
  85. }
  86. }
  87. content, e = ioutil.ReadAll(response.Body)
  88. return
  89. }
  90. func Do(req *http.Request) (resp *http.Response, err error) {
  91. return client.Do(req)
  92. }