You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.go 2.0 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright © 2023 OpenIM open source community. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "fmt"
  17. "math/rand"
  18. "path/filepath"
  19. "time"
  20. )
  21. // GenerateObjectName generate object name with folder and random filename.
  22. func GenerateObjectName(filename string) string {
  23. // generate folder name.
  24. folderName := GenerateFolderName()
  25. // generate random file name.
  26. randomFileName := GenerateFileName(filename)
  27. return fmt.Sprintf("%s/%s", folderName, randomFileName)
  28. }
  29. // GenerateFolderName generate folder name.
  30. func GenerateFolderName() string {
  31. // generate foler name with time string.
  32. return time.Now().Format("20060102")
  33. }
  34. // GenerateFileName generate file name.
  35. func GenerateFileName(filename string) string {
  36. // generate random file name with file extension.
  37. // get file extension.
  38. ext := filepath.Ext(filename)
  39. // generate random file name.
  40. randomFileName := GenerateRandomString(64)
  41. // url encode.
  42. // randomFileName = url.QueryEscape(randomFileName)
  43. return randomFileName + ext
  44. }
  45. // GenerateRandomString generate random string.
  46. func GenerateRandomString(length int) string {
  47. // dataset := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  48. dataset := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()"
  49. rand.Seed(time.Now().UnixNano())
  50. str := make([]byte, length)
  51. for i := 0; i < length; i++ {
  52. str[i] = dataset[rand.Intn(len(dataset))]
  53. }
  54. return string(str)
  55. }