forked from wundergraph/graphql-go-tools
/
init.go
47 lines (37 loc) · 1.14 KB
/
init.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
package websocket
import (
"context"
"encoding/json"
)
// InitFunc is called when the server receives connection init message from the client.
// This can be used to check initial payload to see whether to accept the websocket connection.
type InitFunc func(ctx context.Context, initPayload InitPayload) (context.Context, error)
// InitPayload is a structure that is parsed from the websocket init message payload.
type InitPayload json.RawMessage
// GetString safely gets a string value from the payload. It returns an empty string if the
// payload is nil or the value isn't set.
func (p InitPayload) GetString(key string) string {
if p == nil {
return ""
}
var payload map[string]interface{}
if err := json.Unmarshal(p, &payload); err != nil {
return ""
}
if value, ok := payload[key]; ok {
res, _ := value.(string)
return res
}
return ""
}
// Authorization is a shorthand for getting the Authorization header from the
// payload.
func (p InitPayload) Authorization() string {
if value := p.GetString("Authorization"); value != "" {
return value
}
if value := p.GetString("authorization"); value != "" {
return value
}
return ""
}