-
Notifications
You must be signed in to change notification settings - Fork 479
/
http.go
176 lines (153 loc) · 4.45 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
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"strconv"
"strings"
"time"
"unicode"
"github.com/mitchellh/mapstructure"
"github.com/dapr/components-contrib/bindings"
"github.com/dapr/kit/logger"
)
// HTTPSource is a binding for an http url endpoint invocation
// nolint:golint
type HTTPSource struct {
metadata httpMetadata
client *http.Client
logger logger.Logger
}
type httpMetadata struct {
URL string `mapstructure:"url"`
}
// NewHTTP returns a new HTTPSource.
func NewHTTP(logger logger.Logger) *HTTPSource {
return &HTTPSource{logger: logger}
}
// Init performs metadata parsing.
func (h *HTTPSource) Init(metadata bindings.Metadata) error {
if err := mapstructure.Decode(metadata.Properties, &h.metadata); err != nil {
return err
}
// See guidance on proper HTTP client settings here:
// https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779
dialer := &net.Dialer{
Timeout: 5 * time.Second,
}
netTransport := &http.Transport{
Dial: dialer.Dial,
TLSHandshakeTimeout: 5 * time.Second,
}
h.client = &http.Client{
Timeout: time.Second * 10,
Transport: netTransport,
}
return nil
}
// Operations returns the supported operations for this binding.
func (h *HTTPSource) Operations() []bindings.OperationKind {
return []bindings.OperationKind{
bindings.CreateOperation, // For backward compatibility
"get",
"head",
"post",
"put",
"patch",
"delete",
"options",
"trace",
}
}
// Invoke performs an HTTP request to the configured HTTP endpoint.
func (h *HTTPSource) Invoke(req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) {
u := h.metadata.URL
if req.Metadata != nil {
if path, ok := req.Metadata["path"]; ok {
// Simplicity and no "../../.." type exploits.
u = fmt.Sprintf("%s/%s", strings.TrimRight(u, "/"), strings.TrimLeft(path, "/"))
if strings.Contains(u, "..") {
return nil, fmt.Errorf("invalid path: %s", path)
}
}
}
var body io.Reader
method := strings.ToUpper(string(req.Operation))
// For backward compatibility
if method == "CREATE" {
method = "POST"
}
switch method {
case "PUT", "POST", "PATCH":
body = bytes.NewBuffer(req.Data)
case "GET", "HEAD", "DELETE", "OPTIONS", "TRACE":
default:
return nil, fmt.Errorf("invalid operation: %s", req.Operation)
}
// nolint: noctx
request, err := http.NewRequest(method, u, body)
if err != nil {
return nil, err
}
// Set default values for Content-Type and Accept headers.
if body != nil {
if _, ok := req.Metadata["Content-Type"]; !ok {
request.Header.Set("Content-Type", "application/json; charset=utf-8")
}
}
if _, ok := req.Metadata["Accept"]; !ok {
request.Header.Set("Accept", "application/json; charset=utf-8")
}
// Any metadata keys that start with a capital letter
// are treated as request headers
for mdKey, mdValue := range req.Metadata {
keyAsRunes := []rune(mdKey)
if len(keyAsRunes) > 0 && unicode.IsUpper(keyAsRunes[0]) {
request.Header.Set(mdKey, mdValue)
}
}
// Send the question
resp, err := h.client.Do(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Read the response body. For empty responses (e.g. 204 No Content)
// `b` will be an empty slice.
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
metadata := make(map[string]string, len(resp.Header)+2)
// Include status code & desc
metadata["statusCode"] = strconv.Itoa(resp.StatusCode)
metadata["status"] = resp.Status
// Response headers are mapped from `map[string][]string` to `map[string]string`
// where headers with multiple values are delimited with ", ".
for key, values := range resp.Header {
metadata[key] = strings.Join(values, ", ")
}
// Create an error for non-200 status codes.
if resp.StatusCode/100 != 2 {
err = fmt.Errorf("received status code %d", resp.StatusCode)
}
return &bindings.InvokeResponse{
Data: b,
Metadata: metadata,
}, err
}