forked from smarty/cproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy_protocol_initializer.go
36 lines (30 loc) · 1.06 KB
/
proxy_protocol_initializer.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
package cproxy
import (
"fmt"
"io"
"net"
"strings"
)
type proxyProtocolInitializer struct{}
func newProxyProtocolInitializer() *proxyProtocolInitializer {
return &proxyProtocolInitializer{}
}
func (this *proxyProtocolInitializer) Initialize(client, server Socket) bool {
header := formatHeader(client.RemoteAddr(), server.RemoteAddr())
_, err := io.WriteString(server, header)
return err == nil
}
func formatHeader(client, server net.Addr) string {
clientAddress, clientPort := parseAddress(client.String())
serverAddress, serverPort := parseAddress(server.String())
if strings.Contains(clientAddress, ":") {
return fmt.Sprintf(proxyProtocolIPv6Preamble, clientAddress, serverAddress, clientPort, serverPort)
}
return fmt.Sprintf(proxyProtocolIPv4Preamble, clientAddress, serverAddress, clientPort, serverPort)
}
func parseAddress(address string) (string, string) {
address, port, _ := net.SplitHostPort(address)
return address, port
}
const proxyProtocolIPv4Preamble = "PROXY TCP4 %s %s %s %s\r\n"
const proxyProtocolIPv6Preamble = "PROXY TCP6 %s %s %s %s\r\n"