send_code.go 887 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package service
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "time"
  7. "youngee_b_api/consts"
  8. "youngee_b_api/model/system_model"
  9. "youngee_b_api/redis"
  10. )
  11. var SendCode *sendCode
  12. func SendCodeInit(config *system_model.Session) {
  13. sendCode := new(sendCode)
  14. sendCode.sessionTTL = time.Duration(config.TTL) * time.Minute
  15. SendCode = sendCode
  16. }
  17. type sendCode struct {
  18. sessionTTL time.Duration
  19. }
  20. func (s *sendCode) GetCode(ctx context.Context) string {
  21. rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
  22. vcode := fmt.Sprintf("%06v", rnd.Int31n(1000000))
  23. return vcode
  24. }
  25. func (s *sendCode) SetSession(ctx context.Context, phone string, vcode string) error {
  26. err := redis.Set(ctx, s.getRedisKey(phone), vcode, s.sessionTTL)
  27. if err != nil {
  28. return err
  29. }
  30. return nil
  31. }
  32. func (s *sendCode) getRedisKey(key string) string {
  33. return fmt.Sprintf("%s%s", consts.SessionRedisPrefix, key)
  34. }