aboutsummaryrefslogtreecommitdiff
path: root/rpc.go
blob: 1f3c877fccf3ca5c86162d0d356ce554d6beba30 (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
package goxy

import (
	"errors"
	"fmt"
	"net/rpc"
)

var (
	ErrNoHost    = errors.New("Both Host and Upstream are required")
	ErrNoCert    = errors.New("Certificate and Key are required")
	ErrEmptyHost = errors.New("Empty Host value")
)

const RPCPort = ":8000"

type GoXY struct {
	server *Server
}

func init() {
	rpc.HandleHTTP()
}

func registerRPC(s *Server) error {
	return rpc.Register(&GoXY{s})
}

func DialRPC(server string) (*rpc.Client, error) {
	return rpc.DialHTTP("tcp", server)
}

// Add adds a new route
func (s *GoXY) Add(r Route, _ *struct{}) error {
	if r.Host == "" || r.Upstream == "" {
		return ErrNoHost
	}
	slug, isTLS, err := Slug(r.Host)
	if err != nil {
		return err
	}
	if isTLS && (r.Cert == nil || r.Key == nil) {
		return ErrNoCert
	}
	s.server.Routes[slug] = r
	defer s.server.Save(s.server.DataFile)
	return s.server.UpdateMux()
}

// Del removes a route
func (s *GoXY) Del(host string, _ *struct{}) error {
	slug, _, err := Slug(host)
	if err != nil {
		return err
	}
	delete(s.server.Routes, slug)
	defer s.server.Save(s.server.DataFile)
	return s.server.UpdateMux()
}

// List routes
func (s GoXY) List(_ struct{}, ret *[]string) error {
	for _, v := range s.server.Routes {
		*ret = append(*ret, fmt.Sprint(v))
	}
	return nil
}