This repository has been archived by the owner on Mar 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
lambdahttp.go
95 lines (78 loc) · 1.73 KB
/
lambdahttp.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
package main
import (
"context"
"encoding/json"
"github.com/glassechidna/serverlessish/lambdaruntime"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"io/ioutil"
"net/http"
"os"
)
func main() {
ctx := context.Background()
c := &http.Client{}
if os.Getenv("LH_VERBOSE") != "" {
c.Transport = &verboseTransport{http.DefaultTransport}
}
runtime := lambdaruntime.New(c)
register, err := runtime.ExtensionRegister(ctx, "INVOKE")
if err != nil {
panic(err)
}
identifier := register.Identifier
group, ctx := errgroup.WithContext(ctx)
group.Go(func() error {
for {
_, err = runtime.ExtensionNext(ctx, identifier)
if err != nil {
return errors.WithStack(err)
}
}
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
waitForHealthy(ctx, port)
group.Go(func() error {
for {
next, err := runtime.FunctionNext(ctx)
if err != nil {
return errors.WithStack(err)
}
req, isHttpRequest, err := httpRequestForLambdaInvocation(next, port)
if err != nil {
return errors.WithStack(err)
}
funcResp, err := c.Do(req)
if err != nil {
return errors.WithStack(err)
}
var responseBody []byte
if isHttpRequest {
lambdaResp, err := lambdaResponseForHttpResponse(next, funcResp)
if err != nil {
return errors.WithStack(err)
}
responseBody, err = json.Marshal(lambdaResp)
if err != nil {
return errors.WithStack(err)
}
} else {
responseBody, err = ioutil.ReadAll(funcResp.Body)
if err != nil {
return errors.WithStack(err)
}
}
err = runtime.FunctionResponse(ctx, next.RequestId, responseBody)
if err != nil {
return errors.WithStack(err)
}
}
})
err = group.Wait()
if err != nil {
panic(err)
}
}