-
Notifications
You must be signed in to change notification settings - Fork 3
/
elastic_search.go
72 lines (59 loc) · 1.39 KB
/
elastic_search.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package data_store
import (
"net/http"
"sync"
"time"
"github.com/elastic/go-elasticsearch/v8"
log "github.com/shyyawn/go-to/x/logging"
"github.com/shyyawn/go-to/x/source"
"github.com/spf13/viper"
)
const (
ESDefaultTimeout = time.Second
)
type ElasticSearch struct {
client *elasticsearch.Client
lock sync.RWMutex
Hosts []string `mapstructure:"hosts"`
Timeout time.Duration `mapstructure:"timeout"`
ApiKey string `mapstructure:"api_key"`
}
func (ds *ElasticSearch) LoadFromConfig(key string, config *viper.Viper) error {
return source.LoadFromConfig(key, config, ds)
}
func (ds *ElasticSearch) Client() *elasticsearch.Client {
if ds.client != nil {
return ds.client
}
defer ds.lock.Unlock()
ds.lock.Lock()
var err error
//cert, _ := ioutil.ReadFile(*cacert)
if ds.Timeout == 0 {
ds.Timeout = ESDefaultTimeout
}
cfg := elasticsearch.Config{
Addresses: ds.Hosts,
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: ds.Timeout,
//TLSClientConfig: &tls.Config{
// MinVersion: tls.VersionTLS12,
// // ...
//},
},
//Username: "",
//Password: "",
//CACert: cert,
//CertificateFingerprint: fingerPrint,
}
if ds.ApiKey != "" {
cfg.APIKey = ds.ApiKey
}
ds.client, err = elasticsearch.NewClient(cfg)
if err != nil {
log.Error("Unable to connect to elastic search", err)
ds.client = nil
}
return ds.client
}