You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

options.go 1.6 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (C) MongoDB, Inc. 2017-present.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  6. package readpref
  7. import (
  8. "errors"
  9. "time"
  10. "go.mongodb.org/mongo-driver/tag"
  11. )
  12. // ErrInvalidTagSet indicates that an invalid set of tags was specified.
  13. var ErrInvalidTagSet = errors.New("an even number of tags must be specified")
  14. // Option configures a read preference
  15. type Option func(*ReadPref) error
  16. // WithMaxStaleness sets the maximum staleness a
  17. // server is allowed.
  18. func WithMaxStaleness(ms time.Duration) Option {
  19. return func(rp *ReadPref) error {
  20. rp.maxStaleness = ms
  21. rp.maxStalenessSet = true
  22. return nil
  23. }
  24. }
  25. // WithTags sets a single tag set used to match
  26. // a server. The last call to WithTags or WithTagSets
  27. // overrides all previous calls to either method.
  28. func WithTags(tags ...string) Option {
  29. return func(rp *ReadPref) error {
  30. length := len(tags)
  31. if length < 2 || length%2 != 0 {
  32. return ErrInvalidTagSet
  33. }
  34. tagset := make(tag.Set, 0, length/2)
  35. for i := 1; i < length; i += 2 {
  36. tagset = append(tagset, tag.Tag{Name: tags[i-1], Value: tags[i]})
  37. }
  38. return WithTagSets(tagset)(rp)
  39. }
  40. }
  41. // WithTagSets sets the tag sets used to match
  42. // a server. The last call to WithTags or WithTagSets
  43. // overrides all previous calls to either method.
  44. func WithTagSets(tagSets ...tag.Set) Option {
  45. return func(rp *ReadPref) error {
  46. rp.tagSets = tagSets
  47. return nil
  48. }
  49. }