http_util.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package util
  2. import (
  3. "bufio"
  4. "bytes"
  5. "compress/gzip"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "github.com/valyala/fasthttp"
  15. "github.com/chrislusf/seaweedfs/weed/glog"
  16. )
  17. var (
  18. client *http.Client
  19. Transport *http.Transport
  20. )
  21. func init() {
  22. Transport = &http.Transport{
  23. MaxIdleConnsPerHost: 1024,
  24. }
  25. client = &http.Client{
  26. Transport: Transport,
  27. }
  28. }
  29. func PostContent(url string, fnWriteBody func(w *bufio.Writer), fnReqHeader func(*fasthttp.RequestHeader), fnResp func(resp *fasthttp.Response) error) error {
  30. req := fasthttp.AcquireRequest()
  31. resp := fasthttp.AcquireResponse()
  32. defer fasthttp.ReleaseRequest(req)
  33. defer fasthttp.ReleaseResponse(resp)
  34. req.SetRequestURI(url)
  35. req.Header.SetMethod(fasthttp.MethodPost)
  36. fnReqHeader(&req.Header)
  37. req.SetBodyStreamWriter(fnWriteBody)
  38. if err := fasthttp.Do(req, resp); err != nil {
  39. return err
  40. }
  41. if resp.StatusCode() >= 400 {
  42. return fmt.Errorf("%s: %d", url, resp.StatusCode())
  43. }
  44. return fnResp(resp)
  45. }
  46. func PostBytes(url string, body []byte) ([]byte, error) {
  47. r, err := client.Post(url, "", bytes.NewReader(body))
  48. if err != nil {
  49. return nil, fmt.Errorf("Post to %s: %v", url, err)
  50. }
  51. defer r.Body.Close()
  52. if r.StatusCode >= 400 {
  53. return nil, fmt.Errorf("%s: %s", url, r.Status)
  54. }
  55. b, err := ioutil.ReadAll(r.Body)
  56. if err != nil {
  57. return nil, fmt.Errorf("Read response body: %v", err)
  58. }
  59. return b, nil
  60. }
  61. func Post(url string, values url.Values) ([]byte, error) {
  62. r, err := client.PostForm(url, values)
  63. if err != nil {
  64. return nil, err
  65. }
  66. defer r.Body.Close()
  67. b, err := ioutil.ReadAll(r.Body)
  68. if r.StatusCode >= 400 {
  69. if err != nil {
  70. return nil, fmt.Errorf("%s: %d - %s", url, r.StatusCode, string(b))
  71. } else {
  72. return nil, fmt.Errorf("%s: %s", url, r.Status)
  73. }
  74. }
  75. if err != nil {
  76. return nil, err
  77. }
  78. return b, nil
  79. }
  80. // github.com/chrislusf/seaweedfs/unmaintained/repeated_vacuum/repeated_vacuum.go
  81. // may need increasing http.Client.Timeout
  82. func Get(url string) ([]byte, error) {
  83. r, err := client.Get(url)
  84. if err != nil {
  85. return nil, err
  86. }
  87. defer r.Body.Close()
  88. b, err := ioutil.ReadAll(r.Body)
  89. if r.StatusCode >= 400 {
  90. return nil, fmt.Errorf("%s: %s", url, r.Status)
  91. }
  92. if err != nil {
  93. return nil, err
  94. }
  95. return b, nil
  96. }
  97. func Head(url string, fn func(*fasthttp.ResponseHeader)) error {
  98. req := fasthttp.AcquireRequest()
  99. resp := fasthttp.AcquireResponse()
  100. defer fasthttp.ReleaseRequest(req)
  101. defer fasthttp.ReleaseResponse(resp)
  102. req.SetRequestURI(url)
  103. req.Header.SetMethod(fasthttp.MethodHead)
  104. if err := fasthttp.Do(req, resp); err != nil {
  105. return err
  106. }
  107. if resp.StatusCode() >= 400 {
  108. return fmt.Errorf("%s: %d", url, resp.StatusCode())
  109. }
  110. fn(&resp.Header)
  111. return nil
  112. }
  113. func Delete(url string, jwt string) error {
  114. req, err := http.NewRequest("DELETE", url, nil)
  115. if jwt != "" {
  116. req.Header.Set("Authorization", "BEARER "+string(jwt))
  117. }
  118. if err != nil {
  119. return err
  120. }
  121. resp, e := client.Do(req)
  122. if e != nil {
  123. return e
  124. }
  125. defer resp.Body.Close()
  126. body, err := ioutil.ReadAll(resp.Body)
  127. if err != nil {
  128. return err
  129. }
  130. switch resp.StatusCode {
  131. case http.StatusNotFound, http.StatusAccepted, http.StatusOK:
  132. return nil
  133. }
  134. m := make(map[string]interface{})
  135. if e := json.Unmarshal(body, m); e == nil {
  136. if s, ok := m["error"].(string); ok {
  137. return errors.New(s)
  138. }
  139. }
  140. return errors.New(string(body))
  141. }
  142. func GetBufferStream(url string, values url.Values, allocatedBytes []byte, eachBuffer func([]byte)) error {
  143. r, err := client.PostForm(url, values)
  144. if err != nil {
  145. return err
  146. }
  147. defer r.Body.Close()
  148. if r.StatusCode != 200 {
  149. return fmt.Errorf("%s: %s", url, r.Status)
  150. }
  151. for {
  152. n, err := r.Body.Read(allocatedBytes)
  153. if n > 0 {
  154. eachBuffer(allocatedBytes[:n])
  155. }
  156. if err != nil {
  157. if err == io.EOF {
  158. return nil
  159. }
  160. return err
  161. }
  162. }
  163. }
  164. func GetUrlStream(url string, values url.Values, readFn func(io.Reader) error) error {
  165. r, err := client.PostForm(url, values)
  166. if err != nil {
  167. return err
  168. }
  169. defer r.Body.Close()
  170. if r.StatusCode != 200 {
  171. return fmt.Errorf("%s: %s", url, r.Status)
  172. }
  173. return readFn(r.Body)
  174. }
  175. func DownloadFile(fileUrl string) (filename string, header http.Header, rc io.ReadCloser, e error) {
  176. response, err := client.Get(fileUrl)
  177. if err != nil {
  178. return "", nil, nil, err
  179. }
  180. header = response.Header
  181. contentDisposition := response.Header["Content-Disposition"]
  182. if len(contentDisposition) > 0 {
  183. idx := strings.Index(contentDisposition[0], "filename=")
  184. if idx != -1 {
  185. filename = contentDisposition[0][idx+len("filename="):]
  186. filename = strings.Trim(filename, "\"")
  187. }
  188. }
  189. rc = response.Body
  190. return
  191. }
  192. func Do(req *http.Request) (resp *http.Response, err error) {
  193. return client.Do(req)
  194. }
  195. func NormalizeUrl(url string) string {
  196. if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
  197. return url
  198. }
  199. return "http://" + url
  200. }
  201. func ReadUrl(fileUrl string, offset int64, size int, buf []byte, isReadRange bool) (int64, error) {
  202. req, err := http.NewRequest("GET", fileUrl, nil)
  203. if err != nil {
  204. return 0, err
  205. }
  206. if isReadRange {
  207. req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+int64(size)-1))
  208. } else {
  209. req.Header.Set("Accept-Encoding", "gzip")
  210. }
  211. r, err := client.Do(req)
  212. if err != nil {
  213. return 0, err
  214. }
  215. defer r.Body.Close()
  216. if r.StatusCode >= 400 {
  217. return 0, fmt.Errorf("%s: %s", fileUrl, r.Status)
  218. }
  219. var reader io.ReadCloser
  220. contentEncoding := r.Header.Get("Content-Encoding")
  221. switch contentEncoding {
  222. case "gzip":
  223. reader, err = gzip.NewReader(r.Body)
  224. defer reader.Close()
  225. default:
  226. reader = r.Body
  227. }
  228. var (
  229. i, m int
  230. n int64
  231. )
  232. // refers to https://github.com/golang/go/blob/master/src/bytes/buffer.go#L199
  233. // commit id c170b14c2c1cfb2fd853a37add92a82fd6eb4318
  234. for {
  235. m, err = reader.Read(buf[i:])
  236. i += m
  237. n += int64(m)
  238. if err == io.EOF {
  239. return n, nil
  240. }
  241. if err != nil {
  242. return n, err
  243. }
  244. if n == int64(len(buf)) {
  245. break
  246. }
  247. }
  248. // drains the response body to avoid memory leak
  249. data, _ := ioutil.ReadAll(reader)
  250. if len(data) != 0 {
  251. glog.V(1).Infof("%s reader has remaining %d bytes", contentEncoding, len(data))
  252. }
  253. return n, err
  254. }
  255. func ReadUrlAsStream(fileUrl string, offset int64, size int, fn func(data []byte)) (int64, error) {
  256. req, err := http.NewRequest("GET", fileUrl, nil)
  257. if err != nil {
  258. return 0, err
  259. }
  260. req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+int64(size)-1))
  261. r, err := client.Do(req)
  262. if err != nil {
  263. return 0, err
  264. }
  265. defer r.Body.Close()
  266. if r.StatusCode >= 400 {
  267. return 0, fmt.Errorf("%s: %s", fileUrl, r.Status)
  268. }
  269. var (
  270. m int
  271. n int64
  272. )
  273. buf := make([]byte, 64*1024)
  274. for {
  275. m, err = r.Body.Read(buf)
  276. fn(buf[:m])
  277. n += int64(m)
  278. if err == io.EOF {
  279. return n, nil
  280. }
  281. if err != nil {
  282. return n, err
  283. }
  284. }
  285. }
  286. func ReadUrlAsReaderCloser(fileUrl string, rangeHeader string) (io.ReadCloser, error) {
  287. req, err := http.NewRequest("GET", fileUrl, nil)
  288. if err != nil {
  289. return nil, err
  290. }
  291. if rangeHeader != "" {
  292. req.Header.Add("Range", rangeHeader)
  293. }
  294. r, err := client.Do(req)
  295. if err != nil {
  296. return nil, err
  297. }
  298. if r.StatusCode >= 400 {
  299. return nil, fmt.Errorf("%s: %s", fileUrl, r.Status)
  300. }
  301. return r.Body, nil
  302. }