/
http.go
196 lines (160 loc) · 4.87 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package protocols
import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
pb "github.com/buoyantio/bb/gen"
"github.com/buoyantio/bb/service"
"github.com/gogo/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
log "github.com/sirupsen/logrus"
)
var marshaller = &jsonpb.Marshaler{}
type theHTTPServer struct {
httpServer *http.Server
port int
}
type httpHandler struct {
serviceHandler *service.RequestHandler
}
func (s *theHTTPServer) GetID() string {
return fmt.Sprintf("h1-%d", s.port)
}
func (s *theHTTPServer) Shutdown() error {
log.Infof("Shutting down [%s]", s.GetID())
return s.httpServer.Shutdown(context.Background())
}
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
var protoReq pb.TheRequest
if req.ContentLength > 0 {
r, err := unmarshalProtoRequest(req)
if err != nil {
dealWithErrorDuringHandling(w, fmt.Errorf("error unmarshalling the request: %v", err))
return
}
protoReq = r
} else {
newRequestUID := newRequestUID("http", h.serviceHandler.ConfigID())
log.Infof("Received request with empty body, assigning new request UID [%s] to it", newRequestUID)
protoReq = pb.TheRequest{
RequestUID: newRequestUID,
}
}
protoResponse, err := h.serviceHandler.Handle(req.Context(), &protoReq)
if err != nil {
dealWithErrorDuringHandling(w, fmt.Errorf("error handling http request: %v", err))
return
}
log.Infof("Received HTTP request [%s] [%s %s] Body [%+v] Returning response [%+v]", protoReq.RequestUID, req.Method, req.URL, protoReq, protoResponse)
if err = marshalProtoResponse(w, protoResponse); err != nil {
dealWithErrorDuringHandling(w, fmt.Errorf("error marshalling the response: %v", err))
return
}
}
type httpClient struct {
id string
serverURL string
clientForDownsteamServers *http.Client
}
func (c *httpClient) Close() error { return nil }
func (c *httpClient) GetID() string { return c.id }
func (c *httpClient) Send(req *pb.TheRequest) (*pb.TheResponse, error) {
json, err := marshallProtobufToJSON(req)
if err != nil {
return nil, err
}
resp, err := c.clientForDownsteamServers.Post(c.serverURL, "application/json", strings.NewReader(json))
if err != nil {
return nil, err
}
var protoResp pb.TheResponse
defer resp.Body.Close()
err = unmarshalJSONToProtobuf(resp.Body, &protoResp)
return &protoResp, err
}
func newRequestUID(inboundType string, configID string) string {
return fmt.Sprintf("in:%s-sid:%s-%d", inboundType, configID, time.Now().Nanosecond())
}
func marshallProtobufToJSON(msg proto.Message) (string, error) {
json, err := marshaller.MarshalToString(msg)
if err != nil {
return "", err
}
return json, nil
}
func marshalProtoResponse(httpResp http.ResponseWriter, protoResp proto.Message) error {
jsonResponse, err := marshallProtobufToJSON(protoResp)
if err != nil {
return err
}
_, err = fmt.Fprint(httpResp, jsonResponse)
if err != nil {
return err
}
return nil
}
func unmarshalProtoRequest(httpReq *http.Request) (pb.TheRequest, error) {
var protoReq pb.TheRequest
err := unmarshalJSONToProtobuf(httpReq.Body, &protoReq)
return protoReq, err
}
func unmarshalJSONToProtobuf(r io.Reader, out proto.Message) error {
bytes, err := ioutil.ReadAll(r)
if err != nil {
return err
}
bodyAsString := string(bytes)
err = jsonpb.UnmarshalString(bodyAsString, out)
if err != nil {
return errors.New(bodyAsString)
}
return nil
}
func dealWithErrorDuringHandling(w http.ResponseWriter, err error) {
log.Errorf("Error while handling HTTP request: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
func newHTTPHandler(serviceHandler *service.RequestHandler) *httpHandler {
return &httpHandler{
serviceHandler: serviceHandler,
}
}
// NewHTTPServerIfConfigured returns a HTTP-backed Server
func NewHTTPServerIfConfigured(config *service.Config, serviceHandler *service.RequestHandler) (service.Server, error) {
if config.H1ServerPort == -1 {
return nil, nil
}
srv := &http.Server{
Addr: fmt.Sprintf(":%d", config.H1ServerPort),
Handler: newHTTPHandler(serviceHandler),
}
go func() {
log.Infof("HTTP 1.1 server listening on port [%d]", config.H1ServerPort)
srv.ListenAndServe()
}()
return &theHTTPServer{
port: config.H1ServerPort,
httpServer: srv,
}, nil
}
// NewHTTPClientsIfConfigured takes in a Config and returns an instance of HTTP-backed Client for every configured HTTP
// downstream service
func NewHTTPClientsIfConfigured(config *service.Config) ([]service.Client, error) {
clients := make([]service.Client, 0)
httpClientToUse := &http.Client{
Timeout: config.DownstreamConnectionTimeout,
}
for _, serverURL := range config.H1DownstreamServers {
clients = append(clients, &httpClient{
id: serverURL,
serverURL: serverURL,
clientForDownsteamServers: httpClientToUse,
})
}
return clients, nil
}