Skip to content

Instantly share code, notes, and snippets.

@kosorz
Created March 24, 2021 13:07
Show Gist options
  • Save kosorz/9509b25a0addd45bd285426343f6e309 to your computer and use it in GitHub Desktop.
Save kosorz/9509b25a0addd45bd285426343f6e309 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"math"
"net/http"
"os"
"strconv"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// Post - Shape of each post fetched from the server and sent to the frontend
type Post struct {
Title string `json:"title"`
Author string `json:"author"`
Posted float64 `json:"posted"`
}
// Content - Shape of raw response
type Content struct {
Posts []Post
}
// ResponseBody - Shape of lambda response body
type ResponseBody struct {
Posts []Post `json:"posts"`
PerPage int `json:"perPage"`
Page int `json:"page"`
Pages int `json:"pages"`
}
// Paginate - Provides relevant slice of posts
func Paginate(posts []Post, PerPage int, Page int) []Post {
PostsCount := float64(len(posts))
return posts[int(math.Min(float64((Page-1)*PerPage), PostsCount)):int(math.Min(float64((Page*PerPage)), PostsCount))]
}
// HandleRequest - Lambda request handler
func HandleRequest(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
var client = &http.Client{}
content := Content{}
r, err := client.Get(os.Getenv("URL"))
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
defer r.Body.Close()
json.NewDecoder(r.Body).Decode(&content)
PerPage, _ := strconv.Atoi(request.QueryStringParameters["perPage"])
Page, _ := strconv.Atoi(request.QueryStringParameters["page"])
body := ResponseBody{
PerPage: PerPage,
Page: Page,
Posts: Paginate(content.Posts, PerPage, Page),
Pages: int(math.Ceil(float64(len(content.Posts)) / float64(int(PerPage)))),
}
Body, err := json.Marshal(body)
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
return events.APIGatewayProxyResponse{
Body: string(Body),
StatusCode: 200,
Headers: map[string]string{
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
"Access-Control-Allow-Methods": "GET, OPTIONS, POST",
"Access-Control-Allow-Headers": "Content-Type",
},
}, nil
}
func main() {
lambda.Start(HandleRequest)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment