gddo-server: redirect HTTP requests to HTTPS
Per the documentation at
https://cloud.google.com/appengine/docs/flexible/go/how-requests-are-handled,
you can detect whether a request was sent to your App Engine Flex
application with HTTP or HTTPS by checking the X-Forwarded-Proto
header on the request.
This should not interfere with local development since local
development usually does not occur behind a proxy.
I could add tests around either the mux or the apiMux, but those seem
difficult to back out from `func main`.
Fixes golang/gddo#493.
Change-Id: I735d0f8ee650d14a51bf70a3c958429063a48a86
Reviewed-on: https://go-review.googlesource.com/49650
Reviewed-by: Dmitri Shuralyov <shurcool@gmail.com>
Reviewed-by: Tuo Shan <shantuo@google.com>
diff --git a/gddo-server/main.go b/gddo-server/main.go
index 2e301eb..21b1eff 100644
--- a/gddo-server/main.go
+++ b/gddo-server/main.go
@@ -792,6 +792,23 @@
json.NewEncoder(resp).Encode(&data)
}
+// httpsRedirectHandler redirects all requests with an X-Forwarded-Proto: http
+// handler to their https equivalent.
+type httpsRedirectHandler struct {
+ h http.Handler
+}
+
+func (h httpsRedirectHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
+ if req.Header.Get("X-Forwarded-Proto") == "http" {
+ u := *req.URL
+ u.Scheme = "https"
+ u.Host = req.Host
+ http.Redirect(resp, req, u.String(), http.StatusFound)
+ return
+ }
+ h.h.ServeHTTP(resp, req)
+}
+
type rootHandler []struct {
prefix string
h http.Handler
@@ -972,10 +989,9 @@
cacheBusters.Handler = mux
var root http.Handler = rootHandler{
- {"api.", apiMux},
+ {"api.", httpsRedirectHandler{apiMux}},
{"talks.godoc.org", otherDomainHandler{"https", "go-talks.appspot.com"}},
- {"www.godoc.org", otherDomainHandler{"https", "godoc.org"}},
- {"", mux},
+ {"", httpsRedirectHandler{mux}},
}
if gceLogName != "" {
ctx := context.Background()