utils.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (c) [2022] [巴拉迪维 BaratSemet]
  2. // [ohUrlShortener] is licensed under Mulan PSL v2.
  3. // You can use this software according to the terms and conditions of the Mulan PSL v2.
  4. // You may obtain a copy of Mulan PSL v2 at:
  5. // http://license.coscl.org.cn/MulanPSL2
  6. // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  7. // See the Mulan PSL v2 for more details.
  8. package utils
  9. import (
  10. "crypto/sha256"
  11. "fmt"
  12. "log"
  13. "math/rand"
  14. "os"
  15. "strings"
  16. "time"
  17. "github.com/btcsuite/btcd/btcutil/base58"
  18. )
  19. // ExitOnError 退出程序
  20. func ExitOnError(message string, err error) {
  21. if err != nil {
  22. log.Printf("[%s] - %s", message, err)
  23. os.Exit(-1)
  24. }
  25. }
  26. // PrintOnError 打印错误
  27. func PrintOnError(message string, err error) {
  28. if err != nil {
  29. log.Printf("[%s] - %s", message, err)
  30. }
  31. }
  32. // RaiseError 返回错误
  33. func RaiseError(message string) error {
  34. if !EmptyString(message) {
  35. return fmt.Errorf(message)
  36. }
  37. return nil
  38. }
  39. // EmptyString 判断字符串是否为空
  40. func EmptyString(str string) bool {
  41. str = strings.TrimSpace(str)
  42. return strings.EqualFold(str, "")
  43. }
  44. // UserAgentIpHash 生成用户代理和IP的哈希值
  45. func UserAgentIpHash(useragent string, ip string) string {
  46. input := fmt.Sprintf("%s-%s-%s-%d", useragent, ip, time.Now().String(), rand.Int())
  47. data, _ := Sha256Of(input)
  48. str := Base58Encode(data)
  49. return str[:10]
  50. }
  51. // Sha256Of 计算字符串的哈希值
  52. func Sha256Of(input string) ([]byte, error) {
  53. algorithm := sha256.New()
  54. _, err := algorithm.Write([]byte(strings.TrimSpace(input)))
  55. if err != nil {
  56. return nil, err
  57. }
  58. return algorithm.Sum(nil), nil
  59. }
  60. // Base58Encode base58编码
  61. func Base58Encode(data []byte) string {
  62. return base58.Encode(data)
  63. }