aboutsummaryrefslogtreecommitdiff
path: root/route.go
blob: 7e54650efd6f39007ffc61021864545721fd8619 (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 goxy

import (
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"os"
)

// Routes defines a set of routes including correspondent TLS certificates
type Routes map[string]Route

type Route struct {
	Host, Upstream string
	Cert, Key      []byte
	certificate    *tls.Certificate
}

func (r Route) String() string {
	if r.certificate != nil {
		return fmt.Sprintf("%v → %v with TLS", r.Host, r.Upstream)
	}
	return fmt.Sprintf("%v → %v", r.Host, r.Upstream)
}

// GetCertificate returns certificate for SNI negotiation
func (r Routes) GetCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
	host := h.ServerName
	if v, ok := r[host]; ok && v.certificate != nil {
		return v.certificate, nil
	}
	// HACK search for certs without port
	for k, v := range r {
		if k[:len(host)] == host {
			return v.certificate, nil
		}
	}
	return nil, errors.New("no cert for " + host)
}

func (r Routes) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
	for _, v := range r {
		fmt.Fprintln(w, v)
	}
}

func (r Routes) Save(fname string) error {
	fd, err := os.Create(fname)
	if err != nil {
		return err
	}
	defer fd.Close()
	return json.NewEncoder(fd).Encode(r)
}

func (r *Routes) Load(fname string) error {
	fd, err := os.Open(fname)
	if err != nil {
		return err
	}
	defer fd.Close()
	return json.NewDecoder(fd).Decode(r)
}

func Slug(host string) (string, bool, error) {
	h, err := url.Parse(host)
	if err != nil {
		return "", false, err
	}
	if h.Path == "" {
		h.Path = "/"
	}
	return h.Host + h.Path, h.Scheme == "https", nil
}