forked from mmatczuk/go-http-tunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controlmsg.go
87 lines (75 loc) · 1.97 KB
/
controlmsg.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
79
80
81
82
83
84
85
86
87
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package proto
import (
"fmt"
"net/http"
)
// Protocol HTTP headers.
const (
HeaderAction = "T-Action"
HeaderError = "T-Error"
HeaderForwardedBy = "T-Forwarded-By"
HeaderForwardedFor = "T-Forwarded-For"
HeaderPath = "T-Path"
HeaderProtocol = "T-Proto"
)
// Known actions.
const (
ActionProxy string = "proxy"
)
// Known protocol types.
const (
HTTP = "http"
TCP = "tcp"
TCP4 = "tcp4"
TCP6 = "tcp6"
UNIX = "unix"
WS = "ws"
)
// ControlMessage is sent from server to client before streaming data. It's
// used to inform client about the data and action to take. Based on that client
// routes requests to backend services.
type ControlMessage struct {
Action string
Protocol string
ForwardedFor string
ForwardedBy string
Path string
}
// ReadControlMessage reads ControlMessage from HTTP headers.
func ReadControlMessage(h http.Header) (*ControlMessage, error) {
msg := ControlMessage{
Action: h.Get(HeaderAction),
Protocol: h.Get(HeaderProtocol),
ForwardedFor: h.Get(HeaderForwardedFor),
ForwardedBy: h.Get(HeaderForwardedBy),
Path: h.Get(HeaderPath),
}
var missing []string
if msg.Action == "" {
missing = append(missing, HeaderAction)
}
if msg.Protocol == "" {
missing = append(missing, HeaderProtocol)
}
if msg.ForwardedFor == "" {
missing = append(missing, HeaderForwardedFor)
}
if msg.ForwardedBy == "" {
missing = append(missing, HeaderForwardedBy)
}
if len(missing) != 0 {
return nil, fmt.Errorf("missing headers: %s", missing)
}
return &msg, nil
}
// Update writes ControlMessage to HTTP header.
func (c *ControlMessage) Update(h http.Header) {
h.Set(HeaderAction, string(c.Action))
h.Set(HeaderProtocol, c.Protocol)
h.Set(HeaderForwardedFor, c.ForwardedFor)
h.Set(HeaderForwardedBy, c.ForwardedBy)
h.Set(HeaderPath, c.Path)
}