/
http.go
67 lines (52 loc) · 1.54 KB
/
http.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
package distributor
import (
"math"
"net/http"
"github.com/weaveworks/common/httpgrpc"
"github.com/cortexproject/cortex/pkg/util"
"github.com/grafana/loki/pkg/loghttp"
"github.com/grafana/loki/pkg/logproto"
"github.com/grafana/loki/pkg/logql/unmarshal"
unmarshal_legacy "github.com/grafana/loki/pkg/logql/unmarshal/legacy"
)
var contentType = http.CanonicalHeaderKey("Content-Type")
const applicationJSON = "application/json"
// PushHandler reads a snappy-compressed proto from the HTTP body.
func (d *Distributor) PushHandler(w http.ResponseWriter, r *http.Request) {
req, err := ParseRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, err = d.Push(r.Context(), req)
if err == nil {
w.WriteHeader(http.StatusNoContent)
return
}
resp, ok := httpgrpc.HTTPResponseFromError(err)
if ok {
http.Error(w, string(resp.Body), int(resp.Code))
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func ParseRequest(r *http.Request) (*logproto.PushRequest, error) {
var req logproto.PushRequest
switch r.Header.Get(contentType) {
case applicationJSON:
var err error
if loghttp.GetVersion(r.RequestURI) == loghttp.VersionV1 {
err = unmarshal.DecodePushRequest(r.Body, &req)
} else {
err = unmarshal_legacy.DecodePushRequest(r.Body, &req)
}
if err != nil {
return nil, err
}
default:
if _, err := util.ParseProtoReader(r.Context(), r.Body, int(r.ContentLength), math.MaxInt32, &req, util.RawSnappy); err != nil {
return nil, err
}
}
return &req, nil
}