Skip to content

Commit dfedc31

Browse files
committed
Add query parameter parsing to ParseURL()
Before this change, ParseURL would only accept a very restricted set of URLs (it returned an error, if it encountered any parameter). This commit introduces the ability to process URLs like redis://localhost/1?dial_timeout=10s and similar. Go programs which were providing a configuration tunable (e.g. CLI flag, config entry or environment variable) to configure the Redis connection now don't need to perform this task themselves.
1 parent 3ac3452 commit dfedc31

File tree

3 files changed

+221
-19
lines changed

3 files changed

+221
-19
lines changed

example_test.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,20 +39,22 @@ func ExampleNewClient() {
3939
}
4040

4141
func ExampleParseURL() {
42-
opt, err := redis.ParseURL("redis://:qwerty@localhost:6379/1")
42+
opt, err := redis.ParseURL("redis://:qwerty@localhost:6379/1?dial_timeout=5s")
4343
if err != nil {
4444
panic(err)
4545
}
4646
fmt.Println("addr is", opt.Addr)
4747
fmt.Println("db is", opt.DB)
4848
fmt.Println("password is", opt.Password)
49+
fmt.Println("dial timeout is", opt.DialTimeout)
4950

5051
// Create client as usually.
5152
_ = redis.NewClient(opt)
5253

5354
// Output: addr is localhost:6379
5455
// db is 1
5556
// password is qwerty
57+
// dial timeout is 5s
5658
}
5759

5860
func ExampleNewFailoverClient() {

options.go

Lines changed: 137 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"net"
99
"net/url"
1010
"runtime"
11+
"sort"
1112
"strconv"
1213
"strings"
1314
"time"
@@ -192,9 +193,32 @@ func (opt *Options) clone() *Options {
192193
// Scheme is required.
193194
// There are two connection types: by tcp socket and by unix socket.
194195
// Tcp connection:
195-
// redis://<user>:<password>@<host>:<port>/<db_number>
196+
// redis://<user>:<password>@<host>:<port>/<db_number>
196197
// Unix connection:
197198
// unix://<user>:<password>@</path/to/redis.sock>?db=<db_number>
199+
// Most Option fields can be set using query parameters, with the following restrictions:
200+
// - field names are mapped using snake-case conversion: to set MaxRetries, use max_retries
201+
// - only scalar type fields are supported (bool, int, time.Duration)
202+
// - for time.Duration fields, values must be a valid input for time.ParseDuration();
203+
// additionally a plain integer as value (i.e. without unit) is intepreted as seconds
204+
// - to disable a duration field, use value less than or equal to 0; to use the default
205+
// value, leave the value blank or remove the parameter
206+
// - only the last value is interpreted if a parameter is given multiple times
207+
// - fields "network", "addr", "username" and "password" can only be set using other
208+
// URL attributes (scheme, host, userinfo, resp.), query paremeters using these
209+
// names will be treated as unknown parameters
210+
// - unknown parameter names will result in an error
211+
// Examples:
212+
// redis://user:password@localhost:6789/3?dial_timeout=3&db=1&read_timeout=6s&max_retries=2
213+
// is equivalent to:
214+
// &Options{
215+
// Network: "tcp",
216+
// Addr: "localhost:6789",
217+
// DB: 1, // path "/3" was overridden by "&db=1"
218+
// DialTimeout: 3 * time.Second, // no time unit = seconds
219+
// ReadTimeout: 6 * time.Second,
220+
// MaxRetries: 2,
221+
// }
198222
func ParseURL(redisURL string) (*Options, error) {
199223
u, err := url.Parse(redisURL)
200224
if err != nil {
@@ -216,10 +240,6 @@ func setupTCPConn(u *url.URL) (*Options, error) {
216240

217241
o.Username, o.Password = getUserPassword(u)
218242

219-
if len(u.Query()) > 0 {
220-
return nil, errors.New("redis: no options supported")
221-
}
222-
223243
h, p, err := net.SplitHostPort(u.Host)
224244
if err != nil {
225245
h = u.Host
@@ -250,7 +270,7 @@ func setupTCPConn(u *url.URL) (*Options, error) {
250270
o.TLSConfig = &tls.Config{ServerName: h}
251271
}
252272

253-
return o, nil
273+
return setupConnParams(u, o)
254274
}
255275

256276
func setupUnixConn(u *url.URL) (*Options, error) {
@@ -262,19 +282,122 @@ func setupUnixConn(u *url.URL) (*Options, error) {
262282
return nil, errors.New("redis: empty unix socket path")
263283
}
264284
o.Addr = u.Path
265-
266285
o.Username, o.Password = getUserPassword(u)
286+
return setupConnParams(u, o)
287+
}
267288

268-
dbStr := u.Query().Get("db")
269-
if dbStr == "" {
270-
return o, nil // if database is not set, connect to 0 db.
289+
type queryOptions struct {
290+
q url.Values
291+
err error
292+
}
293+
294+
func (o *queryOptions) string(name string) string {
295+
vs := o.q[name]
296+
if len(vs) == 0 {
297+
return ""
271298
}
299+
delete(o.q, name) // enable detection of unknown parameters
300+
return vs[len(vs)-1]
301+
}
272302

273-
db, err := strconv.Atoi(dbStr)
274-
if err != nil {
275-
return nil, fmt.Errorf("redis: invalid database number: %w", err)
303+
func (o *queryOptions) int(name string) int {
304+
s := o.string(name)
305+
if s == "" {
306+
return 0
307+
}
308+
i, err := strconv.Atoi(s)
309+
if err == nil {
310+
return i
311+
}
312+
if o.err == nil {
313+
o.err = fmt.Errorf("redis: invalid %s number: %s", name, err)
314+
}
315+
return 0
316+
}
317+
318+
func (o *queryOptions) duration(name string) time.Duration {
319+
s := o.string(name)
320+
if s == "" {
321+
return 0
322+
}
323+
// try plain number first
324+
if i, err := strconv.Atoi(s); err == nil {
325+
if i <= 0 {
326+
// disable timeouts
327+
return -1
328+
}
329+
return time.Duration(i) * time.Second
330+
}
331+
dur, err := time.ParseDuration(s)
332+
if err == nil {
333+
return dur
334+
}
335+
if o.err == nil {
336+
o.err = fmt.Errorf("redis: invalid %s duration: %w", name, err)
337+
}
338+
return 0
339+
}
340+
341+
func (o *queryOptions) bool(name string) bool {
342+
switch s := o.string(name); s {
343+
case "true", "1":
344+
return true
345+
case "false", "0", "":
346+
return false
347+
default:
348+
if o.err == nil {
349+
o.err = fmt.Errorf("redis: invalid %s boolean: expected true/false/1/0 or an empty string, got %q", name, s)
350+
}
351+
return false
352+
}
353+
}
354+
355+
func (o *queryOptions) remaining() []string {
356+
if len(o.q) == 0 {
357+
return nil
358+
}
359+
keys := make([]string, 0, len(o.q))
360+
for k := range o.q {
361+
keys = append(keys, k)
362+
}
363+
sort.Strings(keys)
364+
return keys
365+
}
366+
367+
// setupConnParams converts query parameters in u to option value in o.
368+
func setupConnParams(u *url.URL, o *Options) (*Options, error) {
369+
q := queryOptions{q: u.Query()}
370+
371+
// compat: a future major release may use q.int("db")
372+
if tmp := q.string("db"); tmp != "" {
373+
db, err := strconv.Atoi(tmp)
374+
if err != nil {
375+
return nil, fmt.Errorf("redis: invalid database number: %w", err)
376+
}
377+
o.DB = db
378+
}
379+
380+
o.MaxRetries = q.int("max_retries")
381+
o.MinRetryBackoff = q.duration("min_retry_backoff")
382+
o.MaxRetryBackoff = q.duration("max_retry_backoff")
383+
o.DialTimeout = q.duration("dial_timeout")
384+
o.ReadTimeout = q.duration("read_timeout")
385+
o.WriteTimeout = q.duration("write_timeout")
386+
o.PoolFIFO = q.bool("pool_fifo")
387+
o.PoolSize = q.int("pool_size")
388+
o.MinIdleConns = q.int("min_idle_conns")
389+
o.MaxConnAge = q.duration("max_conn_age")
390+
o.PoolTimeout = q.duration("pool_timeout")
391+
o.IdleTimeout = q.duration("idle_timeout")
392+
o.IdleCheckFrequency = q.duration("idle_check_frequency")
393+
if q.err != nil {
394+
return nil, q.err
395+
}
396+
397+
// any parameters left?
398+
if r := q.remaining(); len(r) > 0 {
399+
return nil, fmt.Errorf("redis: unexpected option: %s", strings.Join(r, ", "))
276400
}
277-
o.DB = db
278401

279402
return o, nil
280403
}

options_test.go

Lines changed: 81 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,25 @@ func TestParseURL(t *testing.T) {
4040
}, {
4141
url: "redis://foo:bar@localhost:123",
4242
o: &Options{Addr: "localhost:123", Username: "foo", Password: "bar"},
43+
}, {
44+
// multiple params
45+
url: "redis://localhost:123/?db=2&read_timeout=2&pool_fifo=true",
46+
o: &Options{Addr: "localhost:123", DB: 2, ReadTimeout: 2 * time.Second, PoolFIFO: true},
47+
}, {
48+
// special case handling for disabled timeouts
49+
url: "redis://localhost:123/?db=2&idle_timeout=0",
50+
o: &Options{Addr: "localhost:123", DB: 2, IdleTimeout: -1},
51+
}, {
52+
// negative values disable timeouts as well
53+
url: "redis://localhost:123/?db=2&idle_timeout=-1",
54+
o: &Options{Addr: "localhost:123", DB: 2, IdleTimeout: -1},
55+
}, {
56+
// absent timeout values will use defaults
57+
url: "redis://localhost:123/?db=2&idle_timeout=",
58+
o: &Options{Addr: "localhost:123", DB: 2, IdleTimeout: 0},
59+
}, {
60+
url: "redis://localhost:123/?db=2&idle_timeout", // missing "=" at the end
61+
o: &Options{Addr: "localhost:123", DB: 2, IdleTimeout: 0},
4362
}, {
4463
url: "unix:///tmp/redis.sock",
4564
o: &Options{Addr: "/tmp/redis.sock"},
@@ -50,11 +69,30 @@ func TestParseURL(t *testing.T) {
5069
url: "unix://foo:bar@/tmp/redis.sock?db=3",
5170
o: &Options{Addr: "/tmp/redis.sock", Username: "foo", Password: "bar", DB: 3},
5271
}, {
72+
// invalid db format
5373
url: "unix://foo:bar@/tmp/redis.sock?db=test",
5474
err: errors.New(`redis: invalid database number: strconv.Atoi: parsing "test": invalid syntax`),
75+
}, {
76+
// invalid int value
77+
url: "redis://localhost/?pool_size=five",
78+
err: errors.New(`redis: invalid pool_size number: strconv.Atoi: parsing "five": invalid syntax`),
79+
}, {
80+
// invalid bool value
81+
url: "redis://localhost/?pool_fifo=yes",
82+
err: errors.New(`redis: invalid pool_fifo boolean: expected true/false/1/0 or an empty string, got "yes"`),
83+
}, {
84+
// it returns first error
85+
url: "redis://localhost/?db=foo&pool_size=five",
86+
err: errors.New(`redis: invalid database number: strconv.Atoi: parsing "foo": invalid syntax`),
5587
}, {
5688
url: "redis://localhost/?abc=123",
57-
err: errors.New("redis: no options supported"),
89+
err: errors.New("redis: unexpected option: abc"),
90+
}, {
91+
url: "redis://foo@localhost/?username=bar",
92+
err: errors.New("redis: unexpected option: username"),
93+
}, {
94+
url: "redis://localhost/?wrte_timout=10s&abc=123",
95+
err: errors.New("redis: unexpected option: abc, wrte_timout"),
5896
}, {
5997
url: "http://google.com",
6098
err: errors.New("redis: invalid URL scheme: http"),
@@ -98,7 +136,7 @@ func comprareOptions(t *testing.T, actual, expected *Options) {
98136
t.Errorf("got %q, want %q", actual.Addr, expected.Addr)
99137
}
100138
if actual.DB != expected.DB {
101-
t.Errorf("got %q, expected %q", actual.DB, expected.DB)
139+
t.Errorf("DB: got %q, expected %q", actual.DB, expected.DB)
102140
}
103141
if actual.TLSConfig == nil && expected.TLSConfig != nil {
104142
t.Errorf("got nil TLSConfig, expected a TLSConfig")
@@ -107,10 +145,49 @@ func comprareOptions(t *testing.T, actual, expected *Options) {
107145
t.Errorf("got TLSConfig, expected no TLSConfig")
108146
}
109147
if actual.Username != expected.Username {
110-
t.Errorf("got %q, expected %q", actual.Username, expected.Username)
148+
t.Errorf("Username: got %q, expected %q", actual.Username, expected.Username)
111149
}
112150
if actual.Password != expected.Password {
113-
t.Errorf("got %q, expected %q", actual.Password, expected.Password)
151+
t.Errorf("Password: got %q, expected %q", actual.Password, expected.Password)
152+
}
153+
if actual.MaxRetries != expected.MaxRetries {
154+
t.Errorf("MaxRetries: got %v, expected %v", actual.MaxRetries, expected.MaxRetries)
155+
}
156+
if actual.MinRetryBackoff != expected.MinRetryBackoff {
157+
t.Errorf("MinRetryBackoff: got %v, expected %v", actual.MinRetryBackoff, expected.MinRetryBackoff)
158+
}
159+
if actual.MaxRetryBackoff != expected.MaxRetryBackoff {
160+
t.Errorf("MaxRetryBackoff: got %v, expected %v", actual.MaxRetryBackoff, expected.MaxRetryBackoff)
161+
}
162+
if actual.DialTimeout != expected.DialTimeout {
163+
t.Errorf("DialTimeout: got %v, expected %v", actual.DialTimeout, expected.DialTimeout)
164+
}
165+
if actual.ReadTimeout != expected.ReadTimeout {
166+
t.Errorf("ReadTimeout: got %v, expected %v", actual.ReadTimeout, expected.ReadTimeout)
167+
}
168+
if actual.WriteTimeout != expected.WriteTimeout {
169+
t.Errorf("WriteTimeout: got %v, expected %v", actual.WriteTimeout, expected.WriteTimeout)
170+
}
171+
if actual.PoolFIFO != expected.PoolFIFO {
172+
t.Errorf("PoolFIFO: got %v, expected %v", actual.PoolFIFO, expected.PoolFIFO)
173+
}
174+
if actual.PoolSize != expected.PoolSize {
175+
t.Errorf("PoolSize: got %v, expected %v", actual.PoolSize, expected.PoolSize)
176+
}
177+
if actual.MinIdleConns != expected.MinIdleConns {
178+
t.Errorf("MinIdleConns: got %v, expected %v", actual.MinIdleConns, expected.MinIdleConns)
179+
}
180+
if actual.MaxConnAge != expected.MaxConnAge {
181+
t.Errorf("MaxConnAge: got %v, expected %v", actual.MaxConnAge, expected.MaxConnAge)
182+
}
183+
if actual.PoolTimeout != expected.PoolTimeout {
184+
t.Errorf("PoolTimeout: got %v, expected %v", actual.PoolTimeout, expected.PoolTimeout)
185+
}
186+
if actual.IdleTimeout != expected.IdleTimeout {
187+
t.Errorf("IdleTimeout: got %v, expected %v", actual.IdleTimeout, expected.IdleTimeout)
188+
}
189+
if actual.IdleCheckFrequency != expected.IdleCheckFrequency {
190+
t.Errorf("IdleCheckFrequency: got %v, expected %v", actual.IdleCheckFrequency, expected.IdleCheckFrequency)
114191
}
115192
}
116193

0 commit comments

Comments
 (0)