-
Notifications
You must be signed in to change notification settings - Fork 14
/
http.go
93 lines (71 loc) · 1.64 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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package agent
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/horizon/pkg/pb"
)
type httpHandler struct {
url string
}
func HTTPHandler(url string) ServiceHandler {
if !strings.HasPrefix(url, "http://") {
url = "http://" + url
}
return &httpHandler{url}
}
func (h *httpHandler) HandleRequest(ctx context.Context, L hclog.Logger, sctx ServiceContext) error {
proto := sctx.ProtocolId()
if !(proto == "" || proto == "http") {
return fmt.Errorf("unknown protocol: %s", proto)
}
var req pb.Request
_, err := sctx.ReadMarshal(&req)
if err != nil {
return err
}
L.Info("request started", "method", req.Method, "path", req.Path)
hreq, err := http.NewRequestWithContext(ctx, req.Method, h.url+req.Path, sctx.BodyReader())
if err != nil {
return err
}
hreq.Host = req.Host
hreq.URL.RawQuery = req.Query
hreq.URL.Fragment = req.Fragment
if req.Auth != nil {
hreq.URL.User = url.UserPassword(req.Auth.User, req.Auth.Password)
}
for _, h := range req.Headers {
for _, v := range h.Value {
hreq.Header.Add(h.Name, v)
}
}
hresp, err := http.DefaultClient.Do(hreq)
if err != nil {
return err
}
defer hresp.Body.Close()
var resp pb.Response
resp.Code = int32(hresp.StatusCode)
for k, v := range hresp.Header {
resp.Headers = append(resp.Headers, &pb.Header{
Name: k,
Value: v,
})
}
err = sctx.WriteMarshal(1, &resp)
if err != nil {
return err
}
w := sctx.Writer()
defer w.Close()
n, _ := io.Copy(w, hresp.Body)
L.Info("request ended", "size", n)
return nil
}