mediocregopher / radix.v2

Redis client for Go
http://godoc.org/github.com/mediocregopher/radix.v2
MIT License
433 stars 92 forks source link

String concatenation in key #58

Closed krystalcode closed 7 years ago

krystalcode commented 7 years ago

I have a small function in my Go program that prepares the key:

func redisKey(_id int) string { return "user:" + string(_id) }

I use the same function for both SETting and GETting a value: err = storage.client.Cmd("SET", redisKey(_id), user).Err r := storage.client.Cmd("GET", redisKey(_id))

Strangely, I the GET command does not retrieve the value. Upon inspection with SCAN via a redis cli, the key is stored as something on the lines of "user:\x06". When I hardcode the key in SET as "user:12", I can successfully retrieve the value and it is stored as "user:12", verified via redis cli.

This may be something to do with Go string concatenation but, being relatively new to Go, I'd appreciate any thoughts.

mediocregopher commented 7 years ago

Hey there! The problem is in string(_id), which doesn't do what you want it to do (and which I didn't know you could even do). It's converting the raw int value (which I'm guessing was 6) into a string, but 0x06 isn't a printable character so it's being escaped. What you want is strconv.Atoi(_id) which will return the ascii form of the integer.

https://play.golang.org/p/XVSCofPHyd

As a side-note, I think it's not idiomatic in go to prefix variables with underscores, but that won't actually cause any problems. Hope this helps!

krystalcode commented 7 years ago

Great thanks! That was indeed the issue :)