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.

251 lines
5.0 KiB

9 years ago
10 years ago
10 years ago
10 years ago
  1. package util
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "strings"
  12. "github.com/chrislusf/seaweedfs/weed/security"
  13. )
  14. var (
  15. client *http.Client
  16. Transport *http.Transport
  17. )
  18. func init() {
  19. Transport = &http.Transport{
  20. MaxIdleConnsPerHost: 1024,
  21. }
  22. client = &http.Client{Transport: Transport}
  23. }
  24. func PostBytes(url string, body []byte) ([]byte, error) {
  25. r, err := client.Post(url, "application/octet-stream", bytes.NewReader(body))
  26. if err != nil {
  27. return nil, fmt.Errorf("Post to %s: %v", url, err)
  28. }
  29. defer r.Body.Close()
  30. if r.StatusCode >= 400 {
  31. return nil, fmt.Errorf("%s: %s", url, r.Status)
  32. }
  33. b, err := ioutil.ReadAll(r.Body)
  34. if err != nil {
  35. return nil, fmt.Errorf("Read response body: %v", err)
  36. }
  37. return b, nil
  38. }
  39. func Post(url string, values url.Values) ([]byte, error) {
  40. r, err := client.PostForm(url, values)
  41. if err != nil {
  42. return nil, err
  43. }
  44. defer r.Body.Close()
  45. b, err := ioutil.ReadAll(r.Body)
  46. if r.StatusCode >= 400 {
  47. if err != nil {
  48. return nil, fmt.Errorf("%s: %d - %s", url, r.StatusCode, string(b))
  49. } else {
  50. return nil, fmt.Errorf("%s: %s", url, r.Status)
  51. }
  52. }
  53. if err != nil {
  54. return nil, err
  55. }
  56. return b, nil
  57. }
  58. func Get(url string) ([]byte, error) {
  59. r, err := client.Get(url)
  60. if err != nil {
  61. return nil, err
  62. }
  63. defer r.Body.Close()
  64. b, err := ioutil.ReadAll(r.Body)
  65. if r.StatusCode >= 400 {
  66. return nil, fmt.Errorf("%s: %s", url, r.Status)
  67. }
  68. if err != nil {
  69. return nil, err
  70. }
  71. return b, nil
  72. }
  73. func Head(url string) (http.Header, error) {
  74. r, err := client.Head(url)
  75. if err != nil {
  76. return nil, err
  77. }
  78. if r.StatusCode >= 400 {
  79. return nil, fmt.Errorf("%s: %s", url, r.Status)
  80. }
  81. return r.Header, nil
  82. }
  83. func Delete(url string, jwt security.EncodedJwt) error {
  84. req, err := http.NewRequest("DELETE", url, nil)
  85. if jwt != "" {
  86. req.Header.Set("Authorization", "BEARER "+string(jwt))
  87. }
  88. if err != nil {
  89. return err
  90. }
  91. resp, e := client.Do(req)
  92. if e != nil {
  93. return e
  94. }
  95. defer resp.Body.Close()
  96. body, err := ioutil.ReadAll(resp.Body)
  97. if err != nil {
  98. return err
  99. }
  100. switch resp.StatusCode {
  101. case http.StatusNotFound, http.StatusAccepted, http.StatusOK:
  102. return nil
  103. }
  104. m := make(map[string]interface{})
  105. if e := json.Unmarshal(body, m); e == nil {
  106. if s, ok := m["error"].(string); ok {
  107. return errors.New(s)
  108. }
  109. }
  110. return errors.New(string(body))
  111. }
  112. func GetBufferStream(url string, values url.Values, allocatedBytes []byte, eachBuffer func([]byte)) error {
  113. r, err := client.PostForm(url, values)
  114. if err != nil {
  115. return err
  116. }
  117. defer r.Body.Close()
  118. if r.StatusCode != 200 {
  119. return fmt.Errorf("%s: %s", url, r.Status)
  120. }
  121. bufferSize := len(allocatedBytes)
  122. for {
  123. n, err := r.Body.Read(allocatedBytes)
  124. if n == bufferSize {
  125. eachBuffer(allocatedBytes)
  126. }
  127. if err != nil {
  128. if err == io.EOF {
  129. return nil
  130. }
  131. return err
  132. }
  133. }
  134. }
  135. func GetUrlStream(url string, values url.Values, readFn func(io.Reader) error) error {
  136. r, err := client.PostForm(url, values)
  137. if err != nil {
  138. return err
  139. }
  140. defer r.Body.Close()
  141. if r.StatusCode != 200 {
  142. return fmt.Errorf("%s: %s", url, r.Status)
  143. }
  144. return readFn(r.Body)
  145. }
  146. func DownloadUrl(fileUrl string) (filename string, rc io.ReadCloser, e error) {
  147. response, err := client.Get(fileUrl)
  148. if err != nil {
  149. return "", nil, err
  150. }
  151. contentDisposition := response.Header["Content-Disposition"]
  152. if len(contentDisposition) > 0 {
  153. idx := strings.Index(contentDisposition[0], "filename=")
  154. if idx != -1 {
  155. filename = contentDisposition[0][idx+len("filename="):]
  156. filename = strings.Trim(filename, "\"")
  157. }
  158. }
  159. rc = response.Body
  160. return
  161. }
  162. func Do(req *http.Request) (resp *http.Response, err error) {
  163. return client.Do(req)
  164. }
  165. func NormalizeUrl(url string) string {
  166. if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
  167. return url
  168. }
  169. return "http://" + url
  170. }
  171. func ReadUrl(fileUrl string, offset int64, size int, buf []byte) (n int64, e error) {
  172. req, _ := http.NewRequest("GET", fileUrl, nil)
  173. req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+int64(size)))
  174. r, err := client.Do(req)
  175. if err != nil {
  176. return 0, err
  177. }
  178. defer r.Body.Close()
  179. if r.StatusCode >= 400 {
  180. return 0, fmt.Errorf("%s: %s", fileUrl, r.Status)
  181. }
  182. var i, m int
  183. for {
  184. m, err = r.Body.Read(buf[i:])
  185. if m == 0 {
  186. return
  187. }
  188. i += m
  189. n += int64(m)
  190. if err == io.EOF {
  191. return n, nil
  192. }
  193. if e != nil {
  194. return n, e
  195. }
  196. }
  197. }
  198. func ReadUrlAsStream(fileUrl string, offset int64, size int, fn func(data []byte)) (n int64, e error) {
  199. req, _ := http.NewRequest("GET", fileUrl, nil)
  200. req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+int64(size)))
  201. r, err := client.Do(req)
  202. if err != nil {
  203. return 0, err
  204. }
  205. defer r.Body.Close()
  206. if r.StatusCode >= 400 {
  207. return 0, fmt.Errorf("%s: %s", fileUrl, r.Status)
  208. }
  209. var m int
  210. buf := make([]byte, 64*1024)
  211. for {
  212. m, err = r.Body.Read(buf)
  213. if m == 0 {
  214. return
  215. }
  216. fn(buf[:m])
  217. n += int64(m)
  218. if err == io.EOF {
  219. return n, nil
  220. }
  221. if e != nil {
  222. return n, e
  223. }
  224. }
  225. }