Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Created April 29, 2014 21:47
Show Gist options
  • Save peterhellberg/7dec0edfc125fac893af to your computer and use it in GitHub Desktop.
Save peterhellberg/7dec0edfc125fac893af to your computer and use it in GitHub Desktop.
Parsing a Redis connection string for use with go-workers
package main
import (
"fmt"
"net/url"
"strings"
)
func main() {
s := "redis://username:[email protected]:6389/4?pool=25&process=2"
u, err := url.Parse(s)
if err != nil {
panic(err)
}
config := getConfig(u)
fmt.Println(config)
}
func getConfig(u *url.URL) map[string]string {
config := map[string]string{
"server": u.Host,
"database": strings.Trim(u.Path, "/"),
"pool": "30",
"process": "1",
}
for k, v := range u.Query() {
config[k] = v[0]
}
pass, exists := u.User.Password()
if exists {
config["password"] = pass
}
return config
}
@henvo
Copy link

henvo commented Sep 2, 2020

@peterhellberg Thanks for this snippet.
I know I am a little bit late.. but how is the username passed to the configuration?

@peterhellberg
Copy link
Author

peterhellberg commented Sep 3, 2020

@henvo Password is sent via the *url.URL, more specifically the User field: https://golang.org/pkg/net/url/#URL

Redis (before version 6) does not have users, so the username is discarded.

If you are using Redis 6 with the ACL enabled then you’ll need to modify this snippet to also include the username.

https://redis.io/commands/auth

@henvo
Copy link

henvo commented Sep 3, 2020

Thanks so much for the answer!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment