|
| 1 | +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 2 | +// or more contributor license agreements. Licensed under the Elastic License 2.0; |
| 3 | +// you may not use this file except in compliance with the Elastic License 2.0. |
| 4 | + |
| 5 | +package eventhandler |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "io" |
| 11 | + "net/http" |
| 12 | +) |
| 13 | + |
| 14 | +type OTLPTransport struct { |
| 15 | + client *http.Client |
| 16 | + headers http.Header |
| 17 | + url string |
| 18 | +} |
| 19 | + |
| 20 | +func (o *OTLPTransport) SendEvents(ctx context.Context, r io.Reader, ignoreErrs bool) error { |
| 21 | + req, err := http.NewRequestWithContext(ctx, "POST", o.url, r) |
| 22 | + if err != nil { |
| 23 | + return err |
| 24 | + } |
| 25 | + req.Header = o.headers |
| 26 | + |
| 27 | + res, err := o.client.Do(req) |
| 28 | + if err != nil { |
| 29 | + return err |
| 30 | + } |
| 31 | + defer res.Body.Close() |
| 32 | + |
| 33 | + if !ignoreErrs { |
| 34 | + switch res.StatusCode / 100 { |
| 35 | + case 4: |
| 36 | + return fmt.Errorf("unexpected client error: %d", res.StatusCode) |
| 37 | + case 5: |
| 38 | + return fmt.Errorf("unexpected server error: %d", res.StatusCode) |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return nil |
| 43 | +} |
| 44 | + |
| 45 | +func newOTLPTransport(c *http.Client, srvURL, u, apiKey string, headers map[string]string) *OTLPTransport { |
| 46 | + h := make(http.Header) |
| 47 | + h.Set("Content-Encoding", "deflate") |
| 48 | + h.Set("Content-Type", "application/x-json") |
| 49 | + h.Set("Authorization", "ApiKey "+apiKey) |
| 50 | + |
| 51 | + for name, header := range headers { |
| 52 | + h.Set(name, header) |
| 53 | + } |
| 54 | + |
| 55 | + return &OTLPTransport{ |
| 56 | + client: c, |
| 57 | + url: srvURL + u, |
| 58 | + headers: h, |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func NewOTLPLogsTransport() { |
| 63 | + panic("not implemented") |
| 64 | +} |
| 65 | + |
| 66 | +func NewOTLPMetricsTransport(c *http.Client, srvURL, apiKey string, headers map[string]string) Transport { |
| 67 | + return newOTLPTransport(c, srvURL, "/v1/metrics", apiKey, headers) |
| 68 | +} |
| 69 | + |
| 70 | +func NewOTLPTracesTransport(c *http.Client, srvURL, apiKey string, headers map[string]string) Transport { |
| 71 | + return newOTLPTransport(c, srvURL, "/v1/traces", apiKey, headers) |
| 72 | +} |
0 commit comments