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.

252 lines
5.0 KiB

9 years ago
10 years ago
7 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. defer r.Body.Close()
  79. if r.StatusCode >= 400 {
  80. return nil, fmt.Errorf("%s: %s", url, r.Status)
  81. }
  82. return r.Header, nil
  83. }
  84. func Delete(url string, jwt security.EncodedJwt) error {
  85. req, err := http.NewRequest("DELETE", url, nil)
  86. if jwt != "" {
  87. req.Header.Set("Authorization", "BEARER "+string(jwt))
  88. }
  89. if err != nil {
  90. return err
  91. }
  92. resp, e := client.Do(req)
  93. if e != nil {
  94. return e
  95. }
  96. defer resp.Body.Close()
  97. body, err := ioutil.ReadAll(resp.Body)
  98. if err != nil {
  99. return err
  100. }
  101. switch resp.StatusCode {
  102. case http.StatusNotFound, http.StatusAccepted, http.StatusOK:
  103. return nil
  104. }
  105. m := make(map[string]interface{})
  106. if e := json.Unmarshal(body, m); e == nil {
  107. if s, ok := m["error"].(string); ok {
  108. return errors.New(s)
  109. }
  110. }
  111. return errors.New(string(body))
  112. }
  113. func GetBufferStream(url string, values url.Values, allocatedBytes []byte, eachBuffer func([]byte)) error {
  114. r, err := client.PostForm(url, values)
  115. if err != nil {
  116. return err
  117. }
  118. defer r.Body.Close()
  119. if r.StatusCode != 200 {
  120. return fmt.Errorf("%s: %s", url, r.Status)
  121. }
  122. bufferSize := len(allocatedBytes)
  123. for {
  124. n, err := r.Body.Read(allocatedBytes)
  125. if n == bufferSize {
  126. eachBuffer(allocatedBytes)
  127. }
  128. if err != nil {
  129. if err == io.EOF {
  130. return nil
  131. }
  132. return err
  133. }
  134. }
  135. }
  136. func GetUrlStream(url string, values url.Values, readFn func(io.Reader) error) error {
  137. r, err := client.PostForm(url, values)
  138. if err != nil {
  139. return err
  140. }
  141. defer r.Body.Close()
  142. if r.StatusCode != 200 {
  143. return fmt.Errorf("%s: %s", url, r.Status)
  144. }
  145. return readFn(r.Body)
  146. }
  147. func DownloadUrl(fileUrl string) (filename string, rc io.ReadCloser, e error) {
  148. response, err := client.Get(fileUrl)
  149. if err != nil {
  150. return "", nil, err
  151. }
  152. contentDisposition := response.Header["Content-Disposition"]
  153. if len(contentDisposition) > 0 {
  154. idx := strings.Index(contentDisposition[0], "filename=")
  155. if idx != -1 {
  156. filename = contentDisposition[0][idx+len("filename="):]
  157. filename = strings.Trim(filename, "\"")
  158. }
  159. }
  160. rc = response.Body
  161. return
  162. }
  163. func Do(req *http.Request) (resp *http.Response, err error) {
  164. return client.Do(req)
  165. }
  166. func NormalizeUrl(url string) string {
  167. if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
  168. return url
  169. }
  170. return "http://" + url
  171. }
  172. func ReadUrl(fileUrl string, offset int64, size int, buf []byte) (n int64, e error) {
  173. req, _ := http.NewRequest("GET", fileUrl, nil)
  174. req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+int64(size)))
  175. r, err := client.Do(req)
  176. if err != nil {
  177. return 0, err
  178. }
  179. defer r.Body.Close()
  180. if r.StatusCode >= 400 {
  181. return 0, fmt.Errorf("%s: %s", fileUrl, r.Status)
  182. }
  183. var i, m int
  184. for {
  185. m, err = r.Body.Read(buf[i:])
  186. if m == 0 {
  187. return
  188. }
  189. i += m
  190. n += int64(m)
  191. if err == io.EOF {
  192. return n, nil
  193. }
  194. if e != nil {
  195. return n, e
  196. }
  197. }
  198. }
  199. func ReadUrlAsStream(fileUrl string, offset int64, size int, fn func(data []byte)) (n int64, e error) {
  200. req, _ := http.NewRequest("GET", fileUrl, nil)
  201. req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+int64(size)))
  202. r, err := client.Do(req)
  203. if err != nil {
  204. return 0, err
  205. }
  206. defer r.Body.Close()
  207. if r.StatusCode >= 400 {
  208. return 0, fmt.Errorf("%s: %s", fileUrl, r.Status)
  209. }
  210. var m int
  211. buf := make([]byte, 64*1024)
  212. for {
  213. m, err = r.Body.Read(buf)
  214. if m == 0 {
  215. return
  216. }
  217. fn(buf[:m])
  218. n += int64(m)
  219. if err == io.EOF {
  220. return n, nil
  221. }
  222. if e != nil {
  223. return n, e
  224. }
  225. }
  226. }