Created
June 5, 2020 06:20
-
-
Save k-nishijima/79bf3800574b187bca3a15740f366116 to your computer and use it in GitHub Desktop.
301でリダイレクトするためのLambda関数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"net/http" | |
"net/url" | |
"strings" | |
"github.com/aws/aws-lambda-go/events" | |
"github.com/aws/aws-lambda-go/lambda" | |
"golang.org/x/net/html" | |
) | |
// リライトルールを実装(panicしても最悪/blogは返す) | |
func rewrite(path string) (result string) { | |
fmt.Printf("try rewrite = %v\n", path) | |
result = "/blog" | |
defer func() { | |
if err := recover(); err != nil { | |
fmt.Println("recover:", err) | |
result = "/blog" | |
} | |
}() | |
// root や /@user もしくは日本語URLは無視 | |
if strings.Contains(path, "/@") || | |
strings.Contains(path, "%") || | |
"" == path || | |
"/" == path { | |
return | |
} | |
// pathを念の為正規化して、ルールに従ってリダイレクト先作成を試みる | |
u, err := url.Parse("https://blog.r3it.com" + path) | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
normalPath := u.Path | |
if !strings.Contains(normalPath, "-") { | |
return | |
} | |
// - で区切られてる想定されたパスか? | |
slug := normalPath[0:strings.LastIndex(normalPath, "-")] | |
result = "/blog" + slug | |
fmt.Printf(" rewrite <%s> to <%s>\n", path, result) | |
return | |
} | |
func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { | |
fmt.Printf(" : %#v\n", request) | |
hostHeader := request.Headers["Host"] | |
if strings.Contains(hostHeader, "seminar") { | |
return events.APIGatewayProxyResponse{ | |
StatusCode: 301, | |
Headers: map[string]string{ | |
"Location": "https://www.r3it.com/seminarevent", | |
}, | |
}, nil | |
} | |
return events.APIGatewayProxyResponse{ | |
StatusCode: 301, | |
Headers: map[string]string{ | |
"Location": "https://www.r3it.com" + rewrite(request.Path), | |
}, | |
}, nil | |
} | |
func main() { | |
lambda.Start(handler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment