skip to Main Content

When a Lua script returns a table array during an Eval call, how can it be converted to a []string in go?

The redis cli returns bulk replies in the following format.

1) val1
2) val2 

Will go-redis eval function return the bulk entries as

["val1", "val2"] 

2

Answers


  1. You can use the encoding/json package to convert a JSON string to a slice of strings.

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    // jsonString is the JSON string that you want to convert to a slice of strings.
    const jsonString = `["value1", "value2"]`
    
    func main() {
       
        var stringSlice []string
    
        // Unmarshal the JSON string into the stringSlice variable.
        err := json.Unmarshal([]byte(jsonString), &stringSlice)
        if err != nil {
            fmt.Println(err)
            return
        }
    
        
        fmt.Println(stringSlice) // ["value1", "value2"]
    }
    
    Login or Signup to reply.
  2. Redis returns Lua table arrays as RESP2 arrays. The Go client then will map that response to Go native types. The relevant documentation for go-redis is found here: Lua and Go types.

    The tl;dr is that Lua tables are indeed mapped to a bulk reply, and the Go client maps that to a slice of interface: []interface{}.

    Both go-redis script Run and Eval return a *Cmd. You can use methods on this type to retrieve the output as Go types. Result gives (interface{}, error), which you can type-assert to whatever you want, otherwise, StringSlice is a convenience getter to retrieve []string right away.

    So it looks like:

    script := redis.NewScript(`
      local foo = {"val1", "val2"}
      return foo
    `)
    
    cmd := script.Run(/* parameters */)
    
    i, err := cmd.Result() // (interface, error)
    // or
    ss, err := cmd.StringSlice() // ([]string, error)
    

    If the values aren’t actually all strings, use Slice to get the []interface{} slice, and then inspect the elements individually.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search