| 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 |
|
| 5 |
package config |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
"net/url" |
| 10 |
"strconv" |
| 11 |
"strings" |
| 12 |
) |
| 13 |
|
| 14 |
// Config represents an Elasticsearch configuration. |
| 15 |
type Config struct { |
| 16 |
URL string |
| 17 |
Index string |
| 18 |
Username string |
| 19 |
Password string |
| 20 |
Shards int |
| 21 |
Replicas int |
| 22 |
Sniff *bool |
| 23 |
Healthcheck *bool |
| 24 |
Infolog string |
| 25 |
Errorlog string |
| 26 |
Tracelog string |
| 27 |
} |
| 28 |
|
| 29 |
// Parse returns the Elasticsearch configuration by extracting it |
| 30 |
// from the URL, its path, and its query string. |
| 31 |
// |
| 32 |
// Example: |
| 33 |
// http://127.0.0.1:9200/store-blobs?shards=1&replicas=0&sniff=false&tracelog=elastic.trace.log |
| 34 |
// |
| 35 |
// The code above will return a URL of http://127.0.0.1:9200, an index name |
| 36 |
// of store-blobs, and the related settings from the query string. |
| 37 |
func Parse(elasticURL string) (*Config, error) { |
| 38 |
cfg := &Config{ |
| 39 |
Shards: 1, |
| 40 |
Replicas: 0, |
| 41 |
Sniff: nil, |
| 42 |
} |
| 43 |
|
| 44 |
uri, err := url.Parse(elasticURL) |
| 45 |
if err != nil { |
| 46 |
return nil, fmt.Errorf("error parsing elastic parameter %q: %v", elasticURL, err) |
| 47 |
} |
| 48 |
index := strings.TrimSuffix(strings.TrimPrefix(uri.Path, "/"), "/") |
| 49 |
if uri.User != nil { |
| 50 |
cfg.Username = uri.User.Username() |
| 51 |
cfg.Password, _ = uri.User.Password() |
| 52 |
} |
| 53 |
uri.User = nil |
| 54 |
|
| 55 |
if i, err := strconv.Atoi(uri.Query().Get("shards")); err == nil { |
| 56 |
cfg.Shards = i |
| 57 |
} |
| 58 |
if i, err := strconv.Atoi(uri.Query().Get("replicas")); err == nil { |
| 59 |
cfg.Replicas = i |
| 60 |
} |
| 61 |
if s := uri.Query().Get("sniff"); s != "" { |
| 62 |
if b, err := strconv.ParseBool(s); err == nil { |
| 63 |
cfg.Sniff = &b |
| 64 |
} |
| 65 |
} |
| 66 |
if s := uri.Query().Get("healthcheck"); s != "" { |
| 67 |
if b, err := strconv.ParseBool(s); err == nil { |
| 68 |
cfg.Healthcheck = &b |
| 69 |
} |
| 70 |
} |
| 71 |
if s := uri.Query().Get("infolog"); s != "" { |
| 72 |
cfg.Infolog = s |
| 73 |
} |
| 74 |
if s := uri.Query().Get("errorlog"); s != "" { |
| 75 |
cfg.Errorlog = s |
| 76 |
} |
| 77 |
if s := uri.Query().Get("tracelog"); s != "" { |
| 78 |
cfg.Tracelog = s |
| 79 |
} |
| 80 |
|
| 81 |
uri.Path = "" |
| 82 |
uri.RawQuery = "" |
| 83 |
cfg.URL = uri.String() |
| 84 |
cfg.Index = index |
| 85 |
|
| 86 |
return cfg, nil |
| 87 |
} |