oss.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
  6. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  7. "hongze/hongze_open_api/services/alarm_msg"
  8. "hongze/hongze_open_api/utils"
  9. "os"
  10. "time"
  11. )
  12. /*
  13. 上传demo
  14. func init() {
  15. fmt.Println("start")
  16. randStr := utils.GetRandStringNoSpecialChar(28)
  17. fileName := randStr + ".jpg"
  18. fmt.Println("fileName:",fileName)
  19. fpath:="./1.png"
  20. resourceUrl,err:=UploadAliyun(fileName,fpath)
  21. if err!=nil {
  22. fmt.Println("UploadAliyun Err:",err.Error())
  23. return
  24. }
  25. fmt.Println("resourceUrl:",resourceUrl)
  26. fmt.Println("end")
  27. }
  28. */
  29. //图片上传到阿里云
  30. func UploadAliyun(filename, filepath string) (string, error) {
  31. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  32. if err != nil {
  33. return "1", err
  34. }
  35. bucket, err := client.Bucket(utils.Bucketname)
  36. if err != nil {
  37. return "2", err
  38. }
  39. path := utils.Upload_dir + time.Now().Format("200601/20060102/")
  40. path += filename
  41. err = bucket.PutObjectFromFile(path, filepath)
  42. if err != nil {
  43. return "3", err
  44. }
  45. path = utils.Imghost + path
  46. return path, err
  47. }
  48. //音频上传到阿里云
  49. func UploadAudioAliyun(filename, filepath string) (string, error) {
  50. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  51. if err != nil {
  52. return "1", err
  53. }
  54. bucket, err := client.Bucket(utils.Bucketname)
  55. if err != nil {
  56. return "2", err
  57. }
  58. path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  59. path += filename
  60. err = bucket.PutObjectFromFile(path, filepath)
  61. if err != nil {
  62. return "3", err
  63. }
  64. path = utils.Imghost + path
  65. return path, err
  66. }
  67. //视频上传到阿里云
  68. func UploadVideoAliyun(filename, filepath, savePath string) error {
  69. defer func() {
  70. os.Remove(filepath)
  71. }()
  72. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  73. if err != nil {
  74. return err
  75. }
  76. bucket, err := client.Bucket(utils.Bucketname)
  77. if err != nil {
  78. return err
  79. }
  80. //path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  81. //path += filename
  82. err = bucket.PutObjectFromFile(savePath, filepath)
  83. if err != nil {
  84. return err
  85. }
  86. //path = utils.Imghost + path
  87. //return path,err
  88. return err
  89. }
  90. var (
  91. RoleArn = "acs:ram::1884217364581072:role/hzossrole"
  92. RoleSessionName = "hzossRole"
  93. RAMAccessKeyId = "LTAI5t9S36LXduhTnECVY6Hn"
  94. RAMAccessKeySecret = "V6FG5bdzjKKqMpqEqxeWijJCdzDCuL"
  95. STSTokenCacheKey = "hongze_admin_sts_token"
  96. )
  97. type STSToken struct {
  98. AccessKeyId string
  99. AccessKeySecret string
  100. SecurityToken string
  101. ExpiredTime string
  102. }
  103. // GetOssSTSToken 获取STSToken
  104. func GetOssSTSToken() (item *STSToken, err error) {
  105. defer func() {
  106. if err != nil {
  107. utils.FileLog.Info(err.Error())
  108. go alarm_msg.SendAlarmMsg("获取STSToken失败, ErrMsg: "+err.Error(), 3)
  109. }
  110. }()
  111. item = new(STSToken)
  112. // 获取缓存中的Token
  113. recent, _ := utils.Rc.RedisString(STSTokenCacheKey)
  114. if recent != "" {
  115. lastToken := new(STSToken)
  116. if e := json.Unmarshal([]byte(recent), &lastToken); e != nil {
  117. err = errors.New("GetOssSTSToken lastToken Unmarshal Err: " + e.Error())
  118. return
  119. }
  120. // 未防止正在上传大文件时Token过期, 将判定的过期时间提前10分钟
  121. afterTime := time.Now().Local().Add(10 * time.Minute)
  122. expired, e := time.ParseInLocation(utils.FormatDateTime, lastToken.ExpiredTime, time.Local)
  123. if e != nil {
  124. err = errors.New("GetOssSTSToken expiredTime Parse Err: " + e.Error())
  125. return
  126. }
  127. if expired.After(afterTime) {
  128. item.AccessKeyId = lastToken.AccessKeyId
  129. item.AccessKeySecret = lastToken.AccessKeySecret
  130. item.SecurityToken = lastToken.SecurityToken
  131. item.ExpiredTime = lastToken.ExpiredTime
  132. return
  133. }
  134. }
  135. // 已过期则获取新的token
  136. newToken, e := NewSTSToken()
  137. if e != nil {
  138. err = errors.New("GetOssSTSToken NewSTSToken Err: " + e.Error())
  139. return
  140. }
  141. newTokenJson, e := json.Marshal(newToken)
  142. if e != nil {
  143. err = errors.New("GetOssSTSToken NewToken JSON Err: " + e.Error())
  144. return
  145. }
  146. // 覆盖缓存
  147. if e := utils.Rc.Put(STSTokenCacheKey, newTokenJson, time.Hour); e != nil {
  148. err = errors.New("GetOssSTSToken SetRedis Err: " + e.Error())
  149. return
  150. }
  151. item = newToken
  152. return
  153. }
  154. // NewSTSToken 获取一个新的STSToken
  155. func NewSTSToken() (item *STSToken, err error) {
  156. defer func() {
  157. if err != nil {
  158. utils.FileLog.Info(err.Error())
  159. }
  160. }()
  161. item = new(STSToken)
  162. client, e := sts.NewClientWithAccessKey("cn-shanghai", RAMAccessKeyId, RAMAccessKeySecret)
  163. if e != nil {
  164. err = errors.New("NewSTSToken NewClient Err: " + e.Error())
  165. return
  166. }
  167. request := sts.CreateAssumeRoleRequest()
  168. request.Scheme = "https"
  169. request.RegionId = "cn-shanghai"
  170. request.RoleArn = RoleArn
  171. now := time.Now().Format(utils.FormatDateTimeUnSpace)
  172. request.RoleSessionName = RoleSessionName + now
  173. request.DurationSeconds = "3600"
  174. response, e := client.AssumeRole(request)
  175. if e != nil {
  176. err = errors.New("NewSTSToken AssumeRole Err: " + e.Error())
  177. return
  178. }
  179. if response != nil {
  180. item.AccessKeyId = response.Credentials.AccessKeyId
  181. item.AccessKeySecret = response.Credentials.AccessKeySecret
  182. item.SecurityToken = response.Credentials.SecurityToken
  183. t, _ := time.Parse(time.RFC3339, response.Credentials.Expiration)
  184. expiration := t.In(time.Local)
  185. item.ExpiredTime = expiration.Format(utils.FormatDateTime)
  186. }
  187. return
  188. }
  189. //后台用于传研报小程序二维码
  190. var (
  191. Bucketname string = "hzchart"
  192. Endpoint string = "oss-cn-shanghai.aliyuncs.com"
  193. Imghost string = "https://hzstatic.hzinsights.com/"
  194. UploadDir string = "static/images/"
  195. AccessKeyId string = "LTAIFMZYQhS2BTvW"
  196. AccessKeySecret string = "12kk1ptCHoGWedhBnKRVW5hRJzq9Fq"
  197. )
  198. // UploadAliyunToDir
  199. func UploadAliyunToDir(filename, filepath, fileDir string) (string, error) {
  200. client, err := oss.New(Endpoint, AccessKeyId, AccessKeySecret)
  201. if err != nil {
  202. return "1", err
  203. }
  204. bucket, err := client.Bucket(Bucketname)
  205. if err != nil {
  206. return "2", err
  207. }
  208. if fileDir == "" {
  209. fileDir = time.Now().Format("200601/20060102/")
  210. }
  211. path := UploadDir + fileDir
  212. path += filename
  213. err = bucket.PutObjectFromFile(path, filepath)
  214. if err != nil {
  215. return "3", err
  216. }
  217. path = Imghost + path
  218. return path, err
  219. }