bfs.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha1"
  7. "encoding/base64"
  8. "fmt"
  9. "hash"
  10. "io"
  11. "io/ioutil"
  12. "mime/multipart"
  13. "net/http"
  14. "path"
  15. "strconv"
  16. "time"
  17. "go-common/app/admin/main/upload/conf"
  18. "go-common/app/admin/main/upload/model"
  19. "go-common/library/ecode"
  20. "go-common/library/log"
  21. )
  22. // Bfs .
  23. type Bfs struct {
  24. bfsURL string
  25. waterMarkURL string
  26. imageGenURL string
  27. client *http.Client
  28. wmClient *http.Client
  29. imageGenClient *http.Client
  30. }
  31. // NewBfs .
  32. func NewBfs(c *conf.Config) *Bfs {
  33. return &Bfs{
  34. bfsURL: c.Bfs.BfsURL,
  35. waterMarkURL: c.Bfs.WaterMarkURL,
  36. imageGenURL: c.Bfs.ImageGenURL,
  37. client: &http.Client{
  38. Timeout: time.Duration(c.Bfs.TimeOut),
  39. },
  40. wmClient: &http.Client{
  41. Timeout: time.Duration(c.Bfs.WmTimeOut),
  42. },
  43. imageGenClient: &http.Client{
  44. Timeout: time.Duration(c.Bfs.ImageGenTimeOut),
  45. },
  46. }
  47. }
  48. func (b *Bfs) waterMark(ctx context.Context, data []byte, contentType, wmKey, wmText string, paddingX, paddingY int, wmScale float64) (res []byte, err error) {
  49. var (
  50. resp *http.Response
  51. bw io.Writer
  52. req *http.Request
  53. ext string
  54. )
  55. buf := new(bytes.Buffer)
  56. w := multipart.NewWriter(buf)
  57. if bw, err = w.CreateFormFile("file", "1.jpg"); err != nil {
  58. return
  59. }
  60. if _, err = bw.Write(data); err != nil {
  61. return
  62. }
  63. w.WriteField("wm_key", wmKey)
  64. w.WriteField("wm_text", wmText)
  65. w.WriteField("padding_x", strconv.Itoa(paddingX))
  66. w.WriteField("padding_y", strconv.Itoa(paddingY))
  67. w.WriteField("wm_scale", strconv.FormatFloat(wmScale, 'f', 2, 64))
  68. if ext = path.Base(contentType); ext == "jpeg" {
  69. ext = "jpg"
  70. }
  71. w.WriteField("ext", fmt.Sprintf(".%s", ext))
  72. if err = w.Close(); err != nil {
  73. return
  74. }
  75. if req, err = http.NewRequest(http.MethodPost, b.waterMarkURL, buf); err != nil {
  76. return
  77. }
  78. req.Header.Set("Content-Type", w.FormDataContentType())
  79. if resp, err = b.wmClient.Do(req); err != nil {
  80. return
  81. }
  82. defer resp.Body.Close()
  83. if resp.StatusCode != http.StatusOK {
  84. log.Error("bfs.waterMark.status(%v)", resp.StatusCode)
  85. if resp.StatusCode == http.StatusRequestEntityTooLarge {
  86. err = ecode.BfsUploadFileTooLarge
  87. } else {
  88. err = ecode.ServerErr
  89. }
  90. return
  91. }
  92. res, err = ioutil.ReadAll(resp.Body)
  93. return
  94. }
  95. // Upload with watermark
  96. func (b *Bfs) Upload(ctx context.Context, up *model.UploadParam, data []byte) (location, etag string, err error) {
  97. var (
  98. res []byte
  99. )
  100. if up.WmKey != "" || up.WmText != "" {
  101. if res, err = b.waterMark(ctx, data, up.ContentType, up.WmKey, up.WmText, up.WmPaddingX, up.WmPaddingY, up.WmScale); err != nil {
  102. log.Error("b.waterMark(%+v) error(%v)", up, err)
  103. return
  104. }
  105. data = res
  106. }
  107. location, etag, err = b.upload(ctx, up.ContentType, up.Auth, up.Bucket, up.FileName, data)
  108. return
  109. }
  110. // SpecificUpload .
  111. func (b *Bfs) SpecificUpload(ctx context.Context, contentType, auth, bucket, fileName string, data []byte) (location, etag string, err error) {
  112. location, etag, err = b.upload(ctx, contentType, auth, bucket, fileName, data)
  113. return
  114. }
  115. func (b *Bfs) upload(ctx context.Context, contentType, auth, bucket, fileName string, data []byte) (location, etag string, err error) {
  116. reqURL := fmt.Sprintf("http://%s/bfs/%s/%s", b.bfsURL, bucket, fileName)
  117. buf := new(bytes.Buffer)
  118. if _, err = buf.Write(data); err != nil {
  119. log.Error("buf.Write error(%v)", err)
  120. return
  121. }
  122. req, err := http.NewRequest("PUT", reqURL, buf)
  123. if err != nil {
  124. log.Error("http.NewRequest() error(%v)", err)
  125. return
  126. }
  127. req.Header.Add("Content-Type", contentType)
  128. req.Header.Add("Authorization", auth)
  129. resp, err := b.client.Do(req)
  130. if err != nil {
  131. log.Error("client.Do error(%v)", err)
  132. return
  133. }
  134. defer resp.Body.Close()
  135. switch resp.StatusCode {
  136. case http.StatusOK:
  137. case http.StatusBadRequest:
  138. err = ecode.BfsRequestErr
  139. return
  140. case http.StatusUnauthorized:
  141. // 验证不通过
  142. err = ecode.BfsUploadAuthErr
  143. return
  144. case http.StatusRequestEntityTooLarge:
  145. err = ecode.FileTooLarge
  146. return
  147. case http.StatusNotFound:
  148. err = ecode.NothingFound
  149. return
  150. case http.StatusMethodNotAllowed:
  151. err = ecode.MethodNotAllowed
  152. return
  153. case http.StatusServiceUnavailable:
  154. err = ecode.BfsUploadServiceUnavailable
  155. return
  156. case http.StatusInternalServerError:
  157. err = ecode.ServerErr
  158. return
  159. default:
  160. err = ecode.BfsUploadStatusErr
  161. return
  162. }
  163. code, err := strconv.Atoi(resp.Header.Get("code"))
  164. if err != nil || code != 200 {
  165. err = ecode.BfsUploadCodeErr
  166. return
  167. }
  168. location = resp.Header.Get("location")
  169. etag = resp.Header.Get("etag")
  170. return
  171. }
  172. // Authorize .
  173. func (b *Bfs) Authorize(key, secret, method, bucket, fileName string, expire int64) (authorization string) {
  174. var (
  175. content string
  176. mac hash.Hash
  177. signature string
  178. )
  179. content = fmt.Sprintf("%s\n%s\n%s\n%d\n", method, bucket, fileName, expire)
  180. mac = hmac.New(sha1.New, []byte(secret))
  181. mac.Write([]byte(content))
  182. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  183. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  184. return
  185. }