-
Notifications
You must be signed in to change notification settings - Fork 0
/
gelastic.go
71 lines (55 loc) · 1.45 KB
/
gelastic.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
package gelastic
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net/http"
)
type Gelastic struct {
ElasticEndpoint *http.Client
ElasticUser string
ElasticPassword string
ElasticTimeFormat string
Address string
Port int
}
func (g *Gelastic) InitClient(Address string, Port int, User string, Pass string) {
g.ElasticEndpoint = &http.Client{
}
g.Address = Address
g.Port = Port
g.ElasticUser = User
g.ElasticPassword = Pass
g.ElasticTimeFormat = "2006-01-02T15:04:05Z07:00"
}
func (g *Gelastic) makeElasticRequest(method string, path string, data []byte) {
req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d/%s", g.Address, g.Port, path), bytes.NewBuffer(data))
if err != nil {
panic(err)
}
req.Close = true
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(g.ElasticUser, g.ElasticPassword)
resp, err := g.ElasticEndpoint.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
str, _ := io.ReadAll(resp.Body)
println(string(str))
}
func (g *Gelastic) AddDocument(index string, data any) {
// first step is to marshal the struct
json, err := json.Marshal(data)
if err != nil {
// on error we warn the user, but do not panic so as to
// avoid losing logs.
println("[Error] Document marshalling was not succesful while creating document.")
return
}
h := sha256.New()
h.Write(json)
g.makeElasticRequest("PUT", fmt.Sprintf("%s/_doc/%x", index, h.Sum(nil)), json)
}