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.

73 lines
1.4 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. )
  9. var (
  10. client *http.Client
  11. Transport *http.Transport
  12. )
  13. func init() {
  14. Transport = &http.Transport{
  15. MaxIdleConnsPerHost: 1024,
  16. }
  17. client = &http.Client{Transport: Transport}
  18. }
  19. func Post(url string, values url.Values) ([]byte, error) {
  20. r, err := client.PostForm(url, values)
  21. if err != nil {
  22. glog.V(0).Infoln(err)
  23. return nil, err
  24. }
  25. defer r.Body.Close()
  26. b, err := ioutil.ReadAll(r.Body)
  27. if err != nil {
  28. glog.V(0).Infoln("read post result from", url, err)
  29. return nil, err
  30. }
  31. return b, nil
  32. }
  33. func Get(url string) ([]byte, error) {
  34. r, err := client.Get(url)
  35. if err != nil {
  36. glog.V(0).Infoln(err)
  37. return nil, err
  38. }
  39. defer r.Body.Close()
  40. b, err := ioutil.ReadAll(r.Body)
  41. if r.StatusCode != 200 {
  42. return nil, fmt.Errorf("%s: %s", url, r.Status)
  43. }
  44. if err != nil {
  45. glog.V(0).Infoln("read get result from", url, err)
  46. return nil, err
  47. }
  48. return b, nil
  49. }
  50. func Delete(url string) error {
  51. req, err := http.NewRequest("DELETE", url, nil)
  52. if err != nil {
  53. glog.V(0).Infoln("failing to delete", url)
  54. return err
  55. }
  56. resp, e := client.Do(req)
  57. if e != nil {
  58. glog.V(0).Infoln(e)
  59. return e
  60. }
  61. defer resp.Body.Close()
  62. if _, err := ioutil.ReadAll(resp.Body); err != nil {
  63. glog.V(0).Infoln("read get result from", url, err)
  64. return err
  65. }
  66. return nil
  67. }