From 8dd08e6e5a640ed61a1fda20fe1ac832802b51f6 Mon Sep 17 00:00:00 2001 From: Vladimir Mihailenco Date: Wed, 22 May 2013 17:56:59 +0300 Subject: [PATCH] Add Lua script helper. --- script.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 script.go diff --git a/script.go b/script.go new file mode 100644 index 00000000..6284a236 --- /dev/null +++ b/script.go @@ -0,0 +1,45 @@ +package redis + +import ( + "crypto/sha1" + "encoding/hex" + "io" + "strings" +) + +type Script struct { + src, hash string +} + +func NewScript(src string) *Script { + h := sha1.New() + io.WriteString(h, src) + return &Script{ + src: src, + hash: hex.EncodeToString(h.Sum(nil)), + } +} + +func (s *Script) Load(c *Client) *StringReq { + return c.ScriptLoad(s.src) +} + +func (s *Script) Exists(c *Client) *BoolSliceReq { + return c.ScriptExists(s.src) +} + +func (s *Script) Eval(c *Client, keys []string, args []string) *IfaceReq { + return c.Eval(s.src, keys, args) +} + +func (s *Script) EvalSha(c *Client, keys []string, args []string) *IfaceReq { + return c.EvalSha(s.hash, keys, args) +} + +func (s *Script) Run(c *Client, keys []string, args []string) *IfaceReq { + r := s.EvalSha(c, keys, args) + if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") { + return s.Eval(c, keys, args) + } + return r +}