-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.go
54 lines (47 loc) · 1.33 KB
/
encode.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
package lambda
import (
"encoding/base64"
"errors"
"net/http"
"github.com/aws/aws-lambda-go/events"
"github.com/jan-xyz/box/example/strsvc/lambda/proto/strsvcv1"
"google.golang.org/protobuf/proto"
)
var errNoUpper = errors.New("unable to uppercase name")
func EncodeAPIGateway(m *strsvcv1.Response) (*events.APIGatewayProxyResponse, error) {
resp, err := proto.Marshal(m)
if err != nil {
return nil, err
}
body := base64.StdEncoding.EncodeToString(resp)
return &events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Body: body,
}, nil
}
func EncodeErrorAPIGateway(err error) *events.APIGatewayProxyResponse {
if errors.Is(err, errNoUpper) {
return &events.APIGatewayProxyResponse{StatusCode: http.StatusBadRequest, Body: "cannot uppercase string"}
}
return &events.APIGatewayProxyResponse{
StatusCode: http.StatusInternalServerError,
Body: "oops, an error happened",
}
}
func EncodeHTTP(m *strsvcv1.Response, w http.ResponseWriter) {
resp, err := proto.Marshal(m)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(resp)
}
func EncodeErrorHTTP(err error, w http.ResponseWriter) {
if errors.Is(err, errNoUpper) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
}