- Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlambda.go
More file actions
Latest commit
105 lines (91 loc) · 2.56 KB
/
Copy pathlambda.go
File metadata and controls
105 lines (91 loc) · 2.56 KB
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
package awslambda
import (
"encoding/base64"
"net/http"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/caddyserver/caddy/caddyhttp/httpserver"
)
// Invoker calls a single AWS Lambda function - can be mocked for tests
typeInvokerinterface {
Invoke(input*lambda.InvokeInput) (*lambda.InvokeOutput, error)
}
// Handler represents a middleware instance that can gateway requests to AWS Lambda
typeHandlerstruct {
Next httpserver.Handler
Configs []*Config
}
// ServeHTTP satisfies the httpserver.Handler interface by proxying
// the request to AWS Lambda via the Invoke function
//
// See: http://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html
//
func (hHandler) ServeHTTP(w http.ResponseWriter, r*http.Request) (int, error) {
conf, invokeInput, err:=h.match(r)
iferr!=nil {
return0, err
}
ifconf==nil||conf.Path==""||invokeInput==nil {
returnh.Next.ServeHTTP(w, r)
}
// Invoke function at AWS
invokeOut, err:=conf.invoker.Invoke(invokeInput)
iferr!=nil {
return0, err
}
// Unpack the reply JSON
reply, err:=ParseReply(invokeOut.Payload)
iferr!=nil {
return0, err
}
// Write the response HTTP headers
fork, vals:=rangereply.Meta.Headers {
for_, v:=rangevals {
w.Header().Add(k, v)
}
}
// Default the Content-Type to application/json if not provided on reply
ifw.Header().Get("content-type") =="" {
w.Header().Set("content-type", "application/json")
}
ifreply.Meta.Status<=0 {
reply.Meta.Status=http.StatusOK
}
w.WriteHeader(reply.Meta.Status)
// Optionally decode the response body
varbodyBytes []byte
ifreply.BodyEncoding=="base64"&&reply.Body!="" {
bodyBytes, err=base64.StdEncoding.DecodeString(reply.Body)
iferr!=nil {
return0, err
}
} else {
bodyBytes= []byte(reply.Body)
}
// Write the response body
_, err=w.Write(bodyBytes)
iferr!=nil||reply.Meta.Status>=400 {
return0, err
}
returnreply.Meta.Status, nil
}
// match finds the best match for a proxy config based on r.
func (hHandler) match(r*http.Request) (*Config, *lambda.InvokeInput, error) {
varc*Config
varinvokeInput*lambda.InvokeInput
varerrerror
varlongestMatchint
for_, conf:=rangeh.Configs {
basePath:=conf.Path
ifhttpserver.Path(r.URL.Path).Matches(basePath) &&len(basePath) >longestMatch {
// Convert the request to Invoke input struct
invokeInput, err=conf.MaybeToInvokeInput(r)
iferr!=nil {
returnc, nil, err
} elseifinvokeInput!=nil {
longestMatch=len(basePath)
c=conf
}
}
}
returnc, invokeInput, nil
}