-
Notifications
You must be signed in to change notification settings - Fork 1
/
serverlessplus.go
179 lines (164 loc) · 5.3 KB
/
serverlessplus.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
package serverlessplus
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/tencentyun/scf-go-lib/functioncontext"
)
const (
// Host is the host of HTTP server
Host = "127.0.0.1"
)
// APIGatewayRequestContext represents a request context
type APIGatewayRequestContext struct {
ServiceID string `json:"serviceId"`
RequestID string `json:"requestId"`
Method string `json:"httpMethod"`
Path string `json:"path"`
SourceIP string `json:"sourceIp"`
Stage string `json:"stage"`
Identity struct {
SecretID *string `json:"secretId"`
} `json:"identity"`
}
// APIGatewayRequest represents an API gateway request
type APIGatewayRequest struct {
Headers map[string]string `json:"headers"`
Method string `json:"httpMethod"`
Path string `json:"path"`
QueryString map[string]interface{} `json:"queryString"`
Body string `json:"body"`
Context APIGatewayRequestContext `json:"requestContext"`
// the following fields are ignored
// HeaderParameters interface{} `json:"headerParameters"`
// PathParameters interface{} `json:"pathParameters"`
// QueryStringParameters interface{} `json:"queryStringParameters"`
}
// APIGatewayResponse represents a API gateway response
type APIGatewayResponse struct {
IsBase64Encoded bool `json:"isBase64Encoded"`
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}
// Handler represents a request handler
type Handler struct {
client *http.Client
host string
port int
binaryMIMETypes map[string]struct{}
}
// NewHandler creates a new handler
func NewHandler(port int) *Handler {
return &Handler{
client: http.DefaultClient,
host: Host,
port: port,
}
}
// WithClient allows user to specify a custom `http.Client`
func (h *Handler) WithClient(c *http.Client) *Handler {
h.client = c
return h
}
// WithBinaryMIMETypes allows user to specify MIME types that should be base64 encoded
func (h *Handler) WithBinaryMIMETypes(types []string) *Handler {
h.binaryMIMETypes = make(map[string]struct{})
for _, t := range types {
h.binaryMIMETypes[t] = struct{}{}
}
return h
}
// Handle processes the incoming request
func (h *Handler) Handle(ctx context.Context, r *APIGatewayRequest) (*APIGatewayResponse, error) {
req := r.toHTTPRequest(ctx, h.port)
resp, err := h.client.Do(req)
if err != nil {
fmt.Printf("send http request failed: %v\n", err)
return &APIGatewayResponse{StatusCode: 500}, err
}
defer resp.Body.Close()
return h.toAPIGatewayResponse(resp)
}
func toQueryString(m map[string]interface{}) string {
values := make(url.Values)
for name, value := range m {
switch value.(type) {
case string:
rawValue, _ := value.(string)
values.Add(name, rawValue)
case []string:
rawValues, _ := value.([]string)
for _, value := range rawValues {
values.Add(name, value)
}
default:
// should not reach here
fmt.Printf("headerName=%s, headerValue=%v\n", name, value)
}
}
return values.Encode()
}
func (r *APIGatewayRequest) toHTTPRequest(ctx context.Context, port int) *http.Request {
// consider replace with `http.NewRequest`
req := http.Request{}
req.Method = r.Method
req.URL = &url.URL{
Scheme: "http",
Host: fmt.Sprintf("%s:%d", Host, port),
Path: r.Path,
RawPath: r.Path,
RawQuery: toQueryString(r.QueryString),
}
req.Header = make(http.Header)
for name, value := range r.Headers {
req.Header.Add(http.CanonicalHeaderKey(name), value)
}
// set request context to header
funcCtx, ok := functioncontext.FromContext(ctx)
if ok {
req.Header.Add(http.CanonicalHeaderKey("x-scf-requestid"), funcCtx.RequestID)
}
req.Header.Add(http.CanonicalHeaderKey("x-apigateway-serviceid"), r.Context.ServiceID)
req.Header.Add(http.CanonicalHeaderKey("x-apigateway-requestid"), r.Context.RequestID)
req.Header.Add(http.CanonicalHeaderKey("x-apigateway-method"), r.Context.Method)
req.Header.Add(http.CanonicalHeaderKey("x-apigateway-path"), r.Context.Path)
req.Header.Add(http.CanonicalHeaderKey("x-apigateway-sourceip"), r.Context.SourceIP)
req.Header.Add(http.CanonicalHeaderKey("x-forwarded-for"), r.Context.SourceIP)
req.Header.Add(http.CanonicalHeaderKey("x-apigateway-stage"), r.Context.Stage)
if r.Context.Identity.SecretID != nil {
req.Header.Add(http.CanonicalHeaderKey("x-apigateway-secretid"), *r.Context.Identity.SecretID)
}
req.Body = ioutil.NopCloser(bytes.NewBufferString(r.Body))
return &req
}
func (h *Handler) toAPIGatewayResponse(r *http.Response) (*APIGatewayResponse, error) {
resp := APIGatewayResponse{
StatusCode: r.StatusCode,
Headers: make(map[string]string),
}
resp.Headers["x-powered-by"] = "serverlessplus"
var contentType string
for name, values := range r.Header {
resp.Headers[name] = values[0]
if strings.ToLower(name) == "content-type" {
contentType = strings.Split(values[0], ";")[0]
}
}
_, resp.IsBase64Encoded = h.binaryMIMETypes[contentType]
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return &APIGatewayResponse{StatusCode: 500}, err
}
if resp.IsBase64Encoded {
resp.Body = base64.StdEncoding.EncodeToString(body)
} else {
resp.Body = string(body)
}
return &resp, nil
}