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.

106 lines
2.1 KiB

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