aboutsummaryrefslogtreecommitdiff
path: root/echo/middleware/www_redirect.go
blob: 905a5cfef0f6ef7a378bb8f0bcd0b9c6fb5c99df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package middleware

import (
	"fmt"
	"net"
	"net/http"
	"strings"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

/*
WWW Redirect Middleware

This is a duplicate of existing functionality in Echo. This exists
because we don't want to prefix www to a request that is an IP address
only, only requests that use hostnames.
*/

type WWWRedirectConfig struct {
	Skipper middleware.Skipper
	Code    int
}

var DefaultWWWRedirectConfig = WWWRedirectConfig{
	Skipper: middleware.DefaultSkipper,
	Code:    http.StatusMovedPermanently,
}

func WWWRedirect() echo.MiddlewareFunc {
	return WWWRedirectWithConfig(DefaultWWWRedirectConfig)
}

func WWWRedirectWithConfig(config WWWRedirectConfig) echo.MiddlewareFunc {
	if config.Skipper == nil {
		config.Skipper = DefaultWWWRedirectConfig.Skipper
	}
	if config.Code == 0 {
		config.Code = DefaultWWWRedirectConfig.Code
	}

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			req := c.Request()

			if config.Skipper(c) || strings.HasPrefix(req.Host, "www.") {
				return next(c)
			}

			host, _, err := net.SplitHostPort(req.Host)
			if err != nil {
				return echo.ErrBadRequest
			}

			// Never prefix an IP with www
			//
			// We have to parse the hostname for something that looks like an IP
			// because the golang http server removes the header from the header
			// map and there's no good way to unambiguously determine if this was
			// a raw IP request or if a hostname was submitted.
			//
			// TLS connections could use the req.TLS.ServerName property which
			// should have the correct hostname but there's no such thing for HTTP.
			// Instead we just try to parse anything that makes it to this point
			// because it should be a small one-time cost for a few requests.
			if ip := net.ParseIP(host); ip != nil {
				return next(c)
			}

			return c.Redirect(
				config.Code,
				fmt.Sprintf("https://www.%s%s", req.Host, req.RequestURI),
			)
		}
	}
}