-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
65 lines (58 loc) · 1.46 KB
/
handler.go
File metadata and controls
65 lines (58 loc) · 1.46 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
package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/aws/aws-lambda-go/events"
)
type EventRequest struct {
N int64 `json:"n"`
}
type EventResponse struct {
Result uint64 `json:"result"`
}
func handler(ctx context.Context, e EventRequest) (EventResponse, error) {
fibN, err := fibonacci(e.N)
if err != nil {
return EventResponse{}, err
}
return EventResponse{Result: fibN}, nil
}
func apiGWHandler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
var evtReq EventRequest
err := json.Unmarshal([]byte(req.Body), &evtReq)
if err != nil {
return apiGWResponse(0, http.StatusInternalServerError, err), nil
}
fibN, err := fibonacci(evtReq.N)
if err != nil {
if errors.Is(err, ErrInvalidInput) {
return apiGWResponse(0, http.StatusBadRequest, err), nil
}
return apiGWResponse(0, http.StatusInternalServerError, err), nil
}
return apiGWResponse(fibN, http.StatusOK, nil), nil
}
func apiGWResponse(result uint64, status int, err error) events.APIGatewayProxyResponse {
resp := events.APIGatewayProxyResponse{
StatusCode: status,
Headers: map[string]string{
"Content-Type": "application/json",
},
}
if err != nil {
resp.Body = err.Error()
return resp
}
evtResp := EventResponse{
Result: result,
}
data, err := json.Marshal(evtResp)
if err != nil {
resp.StatusCode = http.StatusInternalServerError
resp.Body = err.Error()
}
resp.Body = string(data)
return resp
}