aboutsummaryrefslogtreecommitdiff
path: root/echo/middleware/https_redirect.go
diff options
context:
space:
mode:
Diffstat (limited to 'echo/middleware/https_redirect.go')
-rw-r--r--echo/middleware/https_redirect.go75
1 files changed, 75 insertions, 0 deletions
diff --git a/echo/middleware/https_redirect.go b/echo/middleware/https_redirect.go
new file mode 100644
index 0000000..311f1c9
--- /dev/null
+++ b/echo/middleware/https_redirect.go
@@ -0,0 +1,75 @@
1package middleware
2
3/*
4HTTP to HTTPS Redirect Middleware
5
6This is a duplicate of existing functionality in Echo because the Echo default
7middleware doesn't support redirecting to a different HTTPS port which is
8needed in dev environments and some prod environments where the server runs on
9an off-port.
10*/
11
12import (
13 "fmt"
14 "net"
15 "net/http"
16
17 "github.com/labstack/echo/v4"
18 "github.com/labstack/echo/v4/middleware"
19)
20
21type HTTPSRedirectConfig struct {
22 Skipper middleware.Skipper
23 Port int
24 Code int
25}
26
27var DefaultHTTPSRedirectConfig = HTTPSRedirectConfig{
28 Skipper: middleware.DefaultSkipper,
29 Port: 443,
30 Code: http.StatusMovedPermanently,
31}
32
33func HTTPSRedirect() echo.MiddlewareFunc {
34 return HTTPSRedirectWithConfig(DefaultHTTPSRedirectConfig)
35}
36
37func HTTPSRedirectWithConfig(config HTTPSRedirectConfig) echo.MiddlewareFunc {
38 if config.Skipper == nil {
39 config.Skipper = DefaultHTTPSRedirectConfig.Skipper
40 }
41 if config.Code == 0 {
42 config.Code = DefaultHTTPSRedirectConfig.Code
43 }
44 if config.Port == 0 {
45 config.Port = DefaultHTTPSRedirectConfig.Port
46 }
47
48 return func(next echo.HandlerFunc) echo.HandlerFunc {
49 return func(c echo.Context) error {
50 if config.Skipper(c) || c.Scheme() == "https" {
51 return next(c)
52 }
53
54 var err error
55 req := c.Request()
56
57 host := req.URL.Host
58 if host == "" {
59 host, _, err = net.SplitHostPort(req.Host)
60 if err != nil {
61 return echo.ErrBadRequest
62 }
63 }
64
65 // Browers assume 443 if it's an https request, otherwise the port
66 // needs to be specified in the URL
67 redir := fmt.Sprintf("https://%s%s", host, req.RequestURI)
68 if config.Port != 443 {
69 redir = fmt.Sprintf("https://%s:%d%s", host, config.Port, req.RequestURI)
70 }
71
72 return c.Redirect(config.Code, redir)
73 }
74 }
75}