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

52 lines
1.1 KiB

  1. package redis
  2. import (
  3. "crypto/sha1"
  4. "encoding/hex"
  5. "io"
  6. "strings"
  7. )
  8. type scripter interface {
  9. Eval(script string, keys []string, args []string) *Cmd
  10. EvalSha(sha1 string, keys []string, args []string) *Cmd
  11. ScriptExists(scripts ...string) *BoolSliceCmd
  12. ScriptLoad(script string) *StringCmd
  13. }
  14. type Script struct {
  15. src, hash string
  16. }
  17. func NewScript(src string) *Script {
  18. h := sha1.New()
  19. io.WriteString(h, src)
  20. return &Script{
  21. src: src,
  22. hash: hex.EncodeToString(h.Sum(nil)),
  23. }
  24. }
  25. func (s *Script) Load(c scripter) *StringCmd {
  26. return c.ScriptLoad(s.src)
  27. }
  28. func (s *Script) Exists(c scripter) *BoolSliceCmd {
  29. return c.ScriptExists(s.src)
  30. }
  31. func (s *Script) Eval(c scripter, keys []string, args []string) *Cmd {
  32. return c.Eval(s.src, keys, args)
  33. }
  34. func (s *Script) EvalSha(c scripter, keys []string, args []string) *Cmd {
  35. return c.EvalSha(s.hash, keys, args)
  36. }
  37. func (s *Script) Run(c *Client, keys []string, args []string) *Cmd {
  38. r := s.EvalSha(c, keys, args)
  39. if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") {
  40. return s.Eval(c, keys, args)
  41. }
  42. return r
  43. }