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

import (
	"encoding/json"
	"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
}

func (r Route) String() string {
	return fmt.Sprintf("%v → %v", r.Host, r.Upstream)
}

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
}