config.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2012-present Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package config
  5. import (
  6. "fmt"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. )
  11. // Config represents an Elasticsearch configuration.
  12. type Config struct {
  13. URL string
  14. Index string
  15. Username string
  16. Password string
  17. Shards int
  18. Replicas int
  19. Sniff *bool
  20. Infolog string
  21. Errorlog string
  22. Tracelog string
  23. }
  24. // Parse returns the Elasticsearch configuration by extracting it
  25. // from the URL, its path, and its query string.
  26. //
  27. // Example:
  28. // http://127.0.0.1:9200/store-blobs?shards=1&replicas=0&sniff=false&tracelog=elastic.trace.log
  29. //
  30. // The code above will return a URL of http://127.0.0.1:9200, an index name
  31. // of store-blobs, and the related settings from the query string.
  32. func Parse(elasticURL string) (*Config, error) {
  33. cfg := &Config{
  34. Shards: 1,
  35. Replicas: 0,
  36. Sniff: nil,
  37. }
  38. uri, err := url.Parse(elasticURL)
  39. if err != nil {
  40. return nil, fmt.Errorf("error parsing elastic parameter %q: %v", elasticURL, err)
  41. }
  42. index := uri.Path
  43. if strings.HasPrefix(index, "/") {
  44. index = index[1:]
  45. }
  46. if strings.HasSuffix(index, "/") {
  47. index = index[:len(index)-1]
  48. }
  49. if index == "" {
  50. return nil, fmt.Errorf("missing index in elastic parameter %q", elasticURL)
  51. }
  52. if uri.User != nil {
  53. cfg.Username = uri.User.Username()
  54. cfg.Password, _ = uri.User.Password()
  55. }
  56. uri.User = nil
  57. if i, err := strconv.Atoi(uri.Query().Get("shards")); err == nil {
  58. cfg.Shards = i
  59. }
  60. if i, err := strconv.Atoi(uri.Query().Get("replicas")); err == nil {
  61. cfg.Replicas = i
  62. }
  63. if s := uri.Query().Get("sniff"); s != "" {
  64. if b, err := strconv.ParseBool(s); err == nil {
  65. cfg.Sniff = &b
  66. }
  67. }
  68. if s := uri.Query().Get("infolog"); s != "" {
  69. cfg.Infolog = s
  70. }
  71. if s := uri.Query().Get("errorlog"); s != "" {
  72. cfg.Errorlog = s
  73. }
  74. if s := uri.Query().Get("tracelog"); s != "" {
  75. cfg.Tracelog = s
  76. }
  77. uri.Path = ""
  78. uri.RawQuery = ""
  79. cfg.URL = uri.String()
  80. cfg.Index = index
  81. return cfg, nil
  82. }