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.

267 lines
5.3 KiB

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