File size: 1,688 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package app

import (
	"net/http"
	"net/url"
	"strings"
)

func applyMiddleware(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {
	// Needs to be wrapped in reverse order
	// so that the first one listed, is the "outermost"
	// handler, thus preserving the expected run-order.
	for i := len(middleware) - 1; i >= 0; i-- {
		h = middleware[i](h)
	}
	return h
}

func httpRedirect(prefix, from, to string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			if req.URL.Path != from {
				next.ServeHTTP(w, req)
				return
			}

			http.Redirect(w, req, prefix+to, http.StatusTemporaryRedirect)
		})
	}
}

func httpRewriteWith(prefix, from string, fn func(req *http.Request) *http.Request) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			if req.URL.Path == from || (strings.HasSuffix(from, "/") && strings.HasPrefix(req.URL.Path, from)) {
				req = fn(req)
				req.URL.Path = prefix + req.URL.Path
			}

			next.ServeHTTP(w, req)
		})
	}
}

func httpRewrite(prefix, from, to string) func(http.Handler) http.Handler {
	u, err := url.Parse(to)
	if err != nil {
		panic(err)
	}
	uQ := u.Query()

	return httpRewriteWith(prefix, from, func(req *http.Request) *http.Request {
		origPath := req.URL.Path
		req.URL.Path = u.Path
		if strings.HasSuffix(from, "/") {
			req.URL.Path += strings.TrimPrefix(origPath, from)
		}
		q := req.URL.Query()
		for key := range uQ {
			q.Set(key, uQ.Get(key))
		}
		req.URL.RawQuery = q.Encode()
		return req
	})
}