From 02d777a1675d12f0965e974ae8b0e2b1265210ea Mon Sep 17 00:00:00 2001 From: GrĂ©goire DuchĂȘne Date: Tue, 4 Jan 2022 14:16:32 +0000 Subject: Move redirection logic into its own HTTP handler Also, have the non-Lambda version take flags instead of environment variables and add tests for the HTTP handler. --- main_aws.go | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) (limited to 'main_aws.go') diff --git a/main_aws.go b/main_aws.go index 120d6de..4f6f16e 100644 --- a/main_aws.go +++ b/main_aws.go @@ -8,27 +8,38 @@ package main import ( "context" "net/http" + "os" "path" + "strings" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) +var ( + from = os.Getenv("FROM") + to = os.Getenv("TO") + vcs = os.Getenv("VCS") + redir = &redirector{from, to, vcs} +) + func redirect(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { - var ( - pkg = path.Join(req.Headers["Host"], req.Path) - resp = events.APIGatewayProxyResponse{ - Body: GetBody(pkg), - Headers: map[string]string{"Content-Type": "text/html; charset=utf-8"}, - } - ) - if v, ok := req.QueryStringParameters["go-get"]; ok && v == "1" { - resp.StatusCode = http.StatusOK - } else { - resp.Headers["Location"] = "https://pkg.go.dev/" + pkg - resp.StatusCode = http.StatusFound + pkg := path.Join(req.Headers["Host"], req.Path) + if v, ok := req.QueryStringParameters["go-get"]; !ok || v != "1" { + return events.APIGatewayProxyResponse{ + Headers: map[string]string{"Location": "https://pkg.go.dev/" + pkg}, + StatusCode: http.StatusFound, + }, nil + } + var buf strings.Builder + if err := body.Execute(&buf, bodyData{pkg, redir.getRepo(pkg), vcs}); err != nil { + return events.APIGatewayProxyResponse{}, err } - return resp, nil + return events.APIGatewayProxyResponse{ + Body: buf.String(), + Headers: map[string]string{"Content-Type": "text/html; charset=utf-8"}, + StatusCode: http.StatusOK, + }, nil } func main() { -- cgit v1.2.3-70-g09d2