/
httpreverseproxy.go
66 lines (52 loc) · 1.39 KB
/
httpreverseproxy.go
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 reverseproxy
import (
"errors"
"fmt"
"log"
"net/http"
"net/http/httputil"
"regexp"
"strconv"
"github.com/function61/gokit/log/logex"
)
var disallowedPorts = []int{22, 80, 443, 8080}
func Register(mux *http.ServeMux, logger *log.Logger) {
logl := logex.Levels(logger)
reverseProxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
destinationPort, err := destinationPortFromVirtualHost(req.Host)
if err != nil {
logl.Error.Println(err.Error())
// leaving Scheme unset aborts the request gracefully
} else {
req.URL.Scheme = "http"
req.URL.Host = fmt.Sprintf("localhost:%d", destinationPort)
}
},
}
mux.Handle("/", reverseProxy)
}
// 8081.punch.fn61.net => 8081
var destinationPortRe = regexp.MustCompile(`^([0-9]+)\.`)
func destinationPortFromVirtualHost(virtualHost string) (int, error) {
matches := destinationPortRe.FindStringSubmatch(virtualHost)
if matches == nil {
return 0, errors.New("failed to determine destination port from vhost")
}
destinationPort, err := strconv.Atoi(matches[1])
if err != nil { // should not happen
return 0, err
}
if isDisallowedPort(destinationPort) {
return 0, errors.New("destination port is disallowed")
}
return destinationPort, nil
}
func isDisallowedPort(port int) bool {
for _, disallowedPort := range disallowedPorts {
if port == disallowedPort {
return true
}
}
return false
}