create.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package api_management
  2. import (
  3. "adm-management/errors"
  4. v1 "adm-management/pb/v1"
  5. "context"
  6. "crypto/md5"
  7. "encoding/hex"
  8. "encoding/json"
  9. "fmt"
  10. "time"
  11. "git.getensh.com/common/gopkgsv2/id"
  12. "gorm.io/gorm"
  13. "git.getensh.com/common/gopkgsv2/database"
  14. "git.getensh.com/common/gopkgsv2/logger"
  15. "go.uber.org/zap"
  16. "google.golang.org/grpc/status"
  17. )
  18. func CreateKey(ctx context.Context, req *v1.CreateKeyRequest) (reply *v1.CreateKeyReply, err error) {
  19. reply = &v1.CreateKeyReply{}
  20. // 捕获各个task中的异常并返回给调用者
  21. defer func() {
  22. if r := recover(); r != nil {
  23. err = fmt.Errorf("%+v", r)
  24. e := &status.Status{}
  25. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  26. logger.Error("err",
  27. zap.String("system_err", err.Error()),
  28. zap.Stack("stacktrace"))
  29. }
  30. }
  31. }()
  32. createAt := time.Now().Unix()
  33. db := database.DB()
  34. err = db.Exec("INSERT INTO t_adm_key_management(`key`, `desc`, created_at, updated_at) VALUES(?,?,?,?)", generateKey(), req.Desc, createAt, createAt).Error
  35. if err != nil {
  36. if err == gorm.ErrRecordNotFound {
  37. return reply, nil
  38. }
  39. return reply, errors.SystemError
  40. }
  41. return reply, nil
  42. }
  43. func generateKey() string {
  44. uuid, _ := id.GetUniqueID()
  45. ts := time.Now().Unix()
  46. text := fmt.Sprintf("%s%d", uuid, ts)
  47. return MD5(text)
  48. }
  49. func MD5(text string) string {
  50. h := md5.New()
  51. h.Write([]byte(text))
  52. return hex.EncodeToString(h.Sum(nil))
  53. }