net_http.go 728 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package rx
  2. import (
  3. "net/url"
  4. "net/http"
  5. "io/ioutil"
  6. )
  7. type HttpResponse struct {
  8. StatusCode uint
  9. Header http.Header
  10. Body [] byte
  11. }
  12. func HttpGet(url *url.URL) Observable {
  13. return NewGoroutine(func(sender Sender) {
  14. if sender.Context().AlreadyCancelled() {
  15. return
  16. }
  17. res, err := http.Get(url.String())
  18. if err != nil {
  19. sender.Error(err)
  20. return
  21. }
  22. if sender.Context().AlreadyCancelled() {
  23. _ = res.Body.Close()
  24. return
  25. }
  26. body, err := ioutil.ReadAll(res.Body)
  27. if err != nil {
  28. sender.Error(err)
  29. return
  30. }
  31. _ = res.Body.Close()
  32. sender.Next(HttpResponse {
  33. Body: body,
  34. Header: res.Header,
  35. StatusCode: uint(res.StatusCode),
  36. })
  37. sender.Complete()
  38. })
  39. }