forked from sohlich/nats-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
86 lines (76 loc) · 1.93 KB
/
util.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
package natsproxy
import (
"fmt"
"net/http"
"regexp"
"strings"
"github.com/nats-io/nats"
)
var (
pathrgxp = regexp.MustCompile(":[A-z,0-9,$,-,_,.,+,!,*,',(,),\\,]{1,}")
)
const (
// Prefix for Web Socket
// INPUT channel
ws_IN = "WS_IN"
//Prefix for Web Socket
// OUTPUT channel
ws_OUT = "WS_OUT"
)
// URLToNats builds the channel name
// from an URL and Method of http.Request
func URLToNats(method string, urlPath string) string {
subURL := strings.Replace(urlPath, "/", ".", -1)
subURL = fmt.Sprintf("%s:%s", method, subURL)
return subURL
}
// SubscribeURLToNats buils the subscription
// channel name with placeholders (started with ":").
// The placeholders are than used to obtain path variables
func SubscribeURLToNats(method string, urlPath string) string {
subURL := pathrgxp.ReplaceAllString(urlPath, "*")
// subURL = lastpathrgxp.ReplaceAllString(subURL, ".*")
subURL = strings.Replace(subURL, "/", ".", -1)
subURL = fmt.Sprintf("%s:%s", method, subURL)
return subURL
}
// copy the values into protocol buffer
// struct
func copyMap(values map[string][]string) map[string]*Values {
headerMap := make(map[string]*Values, 0)
for k, v := range values {
headerMap[k] = &Values{
v,
}
}
return headerMap
}
func testConnection(conn *nats.Conn) error {
if conn == nil {
return fmt.Errorf("natsproxy: Connection cannot be nil")
}
if conn.Status() != nats.CONNECTED {
return ErrNatsClientNotConnected
}
return nil
}
// IsWebSocketRequest returns a boolean indicating whether the request has the
// headers of a WebSocket handshake request.
func IsWebSocketRequest(r *http.Request) bool {
contains := func(key, val string) bool {
vv := strings.Split(r.Header.Get(key), ",")
for _, v := range vv {
if val == strings.ToLower(strings.TrimSpace(v)) {
return true
}
}
return false
}
if !contains("Connection", "upgrade") {
return false
}
if !contains("Upgrade", "websocket") {
return false
}
return true
}