/
proxy.go
78 lines (62 loc) · 1.52 KB
/
proxy.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
72
73
74
75
76
77
78
package proxy
import (
"errors"
"net/http"
"strconv"
)
type Pool map[string]*Proxy
type Pooler interface {
Pool() Pool
}
type Proxy struct {
Settings *Settings
ConnectionHandler Requester
}
type Settings struct {
ServiceName string
Ports []Port
}
type Port struct {
Number int
Protocol string
Name string
}
type Requester interface {
ProxyRequest(w http.ResponseWriter, r *http.Request, requestedURI, port string, settings *Settings)
}
func NewPool() Pool {
return Pool{}
}
func NewProxySettings(serviceName string, ports []Port) *Settings {
return &Settings{
ServiceName: serviceName,
Ports: ports,
}
}
// PortByNameOrNumber accepts both a port number or a port name.
// It will try to convert the method into an integer and then
// search if there is any port number with that value or any
// port name by the param value.
func (p *Settings) PortByNameOrNumber(portNameOrNumber string) (Port, error) {
intPort, _ := strconv.Atoi(portNameOrNumber)
for _, port := range p.Ports {
if port.Number == intPort || port.Name == portNameOrNumber {
return port, nil
}
}
return Port{}, errors.New("invalid port")
}
func (p *Port) Scheme() (string, error) {
if p.Protocol == "http" || p.Protocol == "https" {
return p.Protocol, nil
}
return "", errors.New("invalid port scheme")
}
// WebsocketProtocolFor returns the proper Websocket protocol
// based on the HTTP protocol
func WebsocketProtocolFor(httpProtocol string) string {
if httpProtocol == "https" {
return "wss"
}
return "ws"
}