-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend.go
74 lines (62 loc) · 1.61 KB
/
send.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
73
74
package lokigrus
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"net/http"
"github.com/MouseHatGames/lokigrus/internal/logproto"
"github.com/golang/snappy"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
func sendBatch(ctx context.Context, entries []*entry, labels string, lokiURL string) error {
adapterEntries := make([]*logproto.EntryAdapter, len(entries))
for i, e := range entries {
adapterEntries[i] = &logproto.EntryAdapter{
Timestamp: ×tamppb.Timestamp{Seconds: e.time},
Line: e.str,
}
}
req := logproto.PushRequest{
Streams: []*logproto.StreamAdapter{
{
Labels: labels,
Entries: adapterEntries,
},
},
}
b, err := proto.Marshal(&req)
if err != nil {
return fmt.Errorf("format push request: %s", err)
}
b = snappy.Encode(nil, b)
_, err = send(ctx, lokiURL, b)
if err != nil {
return fmt.Errorf("send push request: %s", err)
}
return nil
}
func send(ctx context.Context, lokiURL string, buf []byte) (int, error) {
req, err := http.NewRequest("POST", lokiURL, bytes.NewReader(buf))
if err != nil {
return -1, err
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-protobuf")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return -1, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
scanner := bufio.NewScanner(io.LimitReader(resp.Body, 1024))
line := ""
if scanner.Scan() {
line = scanner.Text()
}
err = fmt.Errorf("server returned HTTP status %s (%d): %s", resp.Status, resp.StatusCode, line)
}
return resp.StatusCode, err
}