This repository has been archived by the owner on Aug 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
router.go
71 lines (54 loc) · 1.63 KB
/
router.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
67
68
69
70
71
package router
import (
"crypto/tls"
"fmt"
"log"
"github.com/valyala/fasthttp"
"github.com/tpbowden/swarm-ingress-router/service"
)
// Router holds the current routing table
type Router struct {
routes map[string]service.Service
}
// RouteToService returns the correct HTTP handler for a given service's DNS name
func (r *Router) RouteToService(address string, path string, secure bool) (fasthttp.RequestHandler, bool) {
var handler fasthttp.RequestHandler
route, ok := r.routes[address]
if !ok {
log.Printf("Failed to lookup service for %s", address)
return handler, false
}
if secure && !route.Secure {
return handler, false
}
if secure || !route.ForceTLS {
return NewProxyHandler(route.URL), true
}
redirectAddress := fmt.Sprintf("https://%s%s", address, path)
return NewRedirectHandler(redirectAddress, 301), true
}
// CertificateForService returns the certificate for a service (if one exists)
func (r *Router) CertificateForService(address string) (*tls.Certificate, bool) {
var cert *tls.Certificate
route, ok := r.routes[address]
if !ok {
log.Printf("Failed to lookup service for %s", address)
return cert, false
}
certificate := route.Certificate()
return &certificate, true
}
// UpdateTable is an atomic operation to update the routing table
func (r *Router) UpdateTable(services []service.Service) {
newTable := make(map[string]service.Service)
for _, s := range services {
log.Printf("Registering service for %s", s.DNSName)
s.ParseCertificate()
newTable[s.DNSName] = s
}
r.routes = newTable
}
// NewRouter returns a new instance of the router
func NewRouter() *Router {
return &Router{}
}