-
Notifications
You must be signed in to change notification settings - Fork 32
/
proxy.go
45 lines (35 loc) · 990 Bytes
/
proxy.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
package proxy
import (
"encoding/json"
"fmt"
"net/http"
"github.com/apex/go-apex"
)
// Serve adaptes an http.Handler to the apex.Handler interface.
func Serve(h http.Handler) apex.Handler {
if h == nil {
h = http.DefaultServeMux
}
return &handler{h}
}
// Handler implements the apex.Handler interface and adapts it to an
// http.Handler by converting the incoming event to an http.Request object
type handler struct {
Handler http.Handler
}
// Handle accepts a request from the apex shim and dispatches it to an http.Handler
func (p *handler) Handle(event json.RawMessage, ctx *apex.Context) (interface{}, error) {
proxyEvent := &Event{}
err := json.Unmarshal(event, proxyEvent)
if err != nil {
return nil, fmt.Errorf("Parse proxy event: %s", err)
}
req, err := buildRequest(proxyEvent, ctx)
if err != nil {
return nil, fmt.Errorf("Build request: %s", err)
}
res := &ResponseWriter{}
p.Handler.ServeHTTP(res, req)
res.finish()
return &res.response, nil
}