aboutsummaryrefslogtreecommitdiff
path: root/cmd/go-import-redirect-aws/main.go
diff options
context:
space:
mode:
authorGrégoire Duchêne <gduchene@awhk.org>2022-06-25 10:43:53 +0100
committerGrégoire Duchêne <gduchene@awhk.org>2022-06-25 10:43:53 +0100
commit85e60b26336e9aa36c234df6f2c19fe49042185f (patch)
tree28b100fd688ea6a5dd65707a064744c3c0c2c14e /cmd/go-import-redirect-aws/main.go
parente47a7770f18283405b5fbfddc5c5490eca8080fb (diff)
Split the AWS version into its own module
This allows the rather large AWS Lambda SDK to only be fetched if the command itself is being fetched.
Diffstat (limited to 'cmd/go-import-redirect-aws/main.go')
-rw-r--r--cmd/go-import-redirect-aws/main.go58
1 files changed, 58 insertions, 0 deletions
diff --git a/cmd/go-import-redirect-aws/main.go b/cmd/go-import-redirect-aws/main.go
new file mode 100644
index 0000000..fb758a3
--- /dev/null
+++ b/cmd/go-import-redirect-aws/main.go
@@ -0,0 +1,58 @@
+// SPDX-FileCopyrightText: © 2019 Grégoire Duchêne <gduchene@awhk.org>
+// SPDX-License-Identifier: ISC
+
+package main
+
+import (
+ "context"
+ "net/http"
+ "os"
+ "path"
+ "regexp"
+ "strings"
+
+ "github.com/aws/aws-lambda-go/events"
+ "github.com/aws/aws-lambda-go/lambda"
+
+ "go.awhk.org/go-import-redirect/pkg/redirector"
+)
+
+var transf = redirector.Transformer{
+ Pattern: &redirector.Pattern{regexp.MustCompile(strings.ReplaceAll(os.Getenv("FROM"), `\\`, `\`))},
+ Replacement: os.Getenv("TO"),
+ VCS: os.Getenv("VCS"),
+}
+
+func redirect(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
+ pkg := path.Join(req.Headers["Host"], req.Path)
+
+ if !transf.Pattern.MatchString(pkg) {
+ return events.APIGatewayProxyResponse{StatusCode: http.StatusNotFound}, nil
+ }
+
+ 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
+ }
+
+ data := redirector.TemplateData{
+ Package: pkg,
+ Repository: transf.Pattern.ReplaceAllString(pkg, transf.Replacement),
+ VCS: transf.VCS,
+ }
+ var buf strings.Builder
+ if err := redirector.DefaultTemplate.Execute(&buf, data); err != nil {
+ return events.APIGatewayProxyResponse{}, err
+ }
+ return events.APIGatewayProxyResponse{
+ Body: buf.String(),
+ Headers: map[string]string{"Content-Type": "text/html; charset=utf-8"},
+ StatusCode: http.StatusOK,
+ }, nil
+}
+
+func main() {
+ lambda.Start(redirect)
+}