-
Notifications
You must be signed in to change notification settings - Fork 916
/
http.go
82 lines (70 loc) · 2.26 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package gremlin
import (
"context"
"io"
"io/ioutil"
"net/http"
"net/url"
"entgo.io/ent/dialect/gremlin/encoding/graphson"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
)
type httpTransport struct {
client *http.Client
url string
}
// NewHTTPTransport returns a new http transport.
func NewHTTPTransport(urlStr string, client *http.Client) (RoundTripper, error) {
u, err := url.Parse(urlStr)
if err != nil {
return nil, errors.Wrap(err, "gremlin/http: parsing url")
}
if client == nil {
client = http.DefaultClient
}
return &httpTransport{client, u.String()}, nil
}
// RoundTrip implements RouterTripper interface.
func (t *httpTransport) RoundTrip(ctx context.Context, req *Request) (*Response, error) {
if req.Operation != OpsEval {
return nil, errors.Errorf("gremlin/http: unsupported operation: %q", req.Operation)
}
if _, ok := req.Arguments[ArgsGremlin]; !ok {
return nil, errors.New("gremlin/http: missing query expression")
}
pr, pw := io.Pipe()
defer pr.Close()
go func() {
err := jsoniter.NewEncoder(pw).Encode(req.Arguments)
_ = pw.CloseWithError(errors.Wrap(err, "gremlin/http: encoding request"))
}()
var br io.Reader
{
req, err := http.NewRequest(http.MethodPost, t.url, pr)
if err != nil {
return nil, errors.Wrap(err, "gremlin/http: creating http request")
}
req.Header.Set("Content-Type", "application/json")
rsp, err := t.client.Do(req.WithContext(ctx))
if err != nil {
return nil, errors.Wrap(err, "gremlin/http: posting http request")
}
defer rsp.Body.Close()
if rsp.StatusCode < http.StatusOK || rsp.StatusCode > http.StatusPartialContent {
body, _ := ioutil.ReadAll(rsp.Body)
return nil, errors.Errorf("gremlin/http: status=%q, body=%q", rsp.Status, body)
}
if rsp.ContentLength > MaxResponseSize {
return nil, errors.New("gremlin/http: context length exceeds limit")
}
br = rsp.Body
}
var rsp Response
if err := graphson.NewDecoder(io.LimitReader(br, MaxResponseSize)).Decode(&rsp); err != nil {
return nil, errors.Wrap(err, "gremlin/http: decoding response")
}
return &rsp, nil
}