53 lines
1011 B
Go
53 lines
1011 B
Go
package esmanager
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/elastic/go-elasticsearch/v7"
|
|
)
|
|
|
|
var Instance *Manager
|
|
|
|
type Manager struct {
|
|
client *elasticsearch.Client
|
|
conf *elasticsearch.Config
|
|
}
|
|
|
|
func NewManager(url string, user string, pw string) (*Manager, error) {
|
|
if url == "" {
|
|
return nil, errors.New(fmt.Sprintf("Elastic NewManager url is empty!"))
|
|
}
|
|
cfg := elasticsearch.Config{
|
|
Addresses: []string{url},
|
|
Transport: &http.Transport{
|
|
MaxIdleConnsPerHost: 10,
|
|
IdleConnTimeout: 30,
|
|
},
|
|
Username: user,
|
|
Password: pw,
|
|
}
|
|
return &Manager{conf: &cfg}, nil
|
|
}
|
|
|
|
func (m *Manager) Client() *elasticsearch.Client {
|
|
return m.client
|
|
}
|
|
|
|
func (m *Manager) ClientConnect() error {
|
|
c, err := elasticsearch.NewClient(*m.conf)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
resp, err := c.Ping(c.Ping.WithContext(context.Background()))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if resp.StatusCode != http.StatusOK {
|
|
return errors.New(fmt.Sprintf("%+v", resp))
|
|
}
|
|
m.client = c
|
|
return nil
|
|
} |