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.

97 lines
2.0 KiB

  1. package util
  2. import (
  3. "code.google.com/p/weed-fs/go/glog"
  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 Post(url string, values url.Values) ([]byte, error) {
  21. r, err := client.PostForm(url, values)
  22. if err != nil {
  23. glog.V(0).Infoln(err)
  24. return nil, err
  25. }
  26. defer r.Body.Close()
  27. b, err := ioutil.ReadAll(r.Body)
  28. if err != nil {
  29. glog.V(0).Infoln("read post result from", url, err)
  30. return nil, err
  31. }
  32. return b, nil
  33. }
  34. func Get(url string) ([]byte, error) {
  35. r, err := client.Get(url)
  36. if err != nil {
  37. glog.V(0).Infoln(err)
  38. return nil, err
  39. }
  40. defer r.Body.Close()
  41. b, err := ioutil.ReadAll(r.Body)
  42. if r.StatusCode != 200 {
  43. return nil, fmt.Errorf("%s: %s", url, r.Status)
  44. }
  45. if err != nil {
  46. glog.V(0).Infoln("read get result from", url, err)
  47. return nil, err
  48. }
  49. return b, nil
  50. }
  51. func Delete(url string) error {
  52. req, err := http.NewRequest("DELETE", url, nil)
  53. if err != nil {
  54. glog.V(0).Infoln("failing to delete", url)
  55. return err
  56. }
  57. resp, e := client.Do(req)
  58. if e != nil {
  59. glog.V(0).Infoln(e)
  60. return e
  61. }
  62. defer resp.Body.Close()
  63. if _, err := ioutil.ReadAll(resp.Body); err != nil {
  64. glog.V(0).Infoln("read get result from", url, err)
  65. return err
  66. }
  67. return nil
  68. }
  69. func DownloadUrl(fileUrl string) (filename string, content []byte, e error) {
  70. response, err := client.Get(fileUrl)
  71. if err != nil {
  72. return "", nil, err
  73. }
  74. defer response.Body.Close()
  75. contentDisposition := response.Header["Content-Disposition"]
  76. if len(contentDisposition) > 0 {
  77. glog.V(4).Info("Content-Disposition: ", contentDisposition[0])
  78. if strings.HasPrefix(contentDisposition[0], "filename=") {
  79. filename = contentDisposition[0][len("filename="):]
  80. }
  81. } else {
  82. glog.V(4).Info("No Content-Disposition!")
  83. }
  84. content, e = ioutil.ReadAll(response.Body)
  85. return
  86. }
  87. func Do(req *http.Request) (resp *http.Response, err error) {
  88. return client.Do(req)
  89. }