-
Notifications
You must be signed in to change notification settings - Fork 13
/
WRPHandler.go
90 lines (73 loc) · 2.49 KB
/
WRPHandler.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
88
89
90
// SPDX-FileCopyrightText: 2019 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package main
import (
"net/http"
gokithttp "github.com/go-kit/kit/transport/http"
"github.com/xmidt-org/webpa-common/v2/xhttp"
"github.com/xmidt-org/wrp-go/v3"
"github.com/xmidt-org/wrp-go/v3/wrpcontext"
"github.com/xmidt-org/wrp-go/v3/wrphttp"
)
type nonWRPResponseWriter struct {
http.ResponseWriter
}
func (o *nonWRPResponseWriter) WriteWRP(_ *wrphttp.Entity) (int, error) {
return 0, nil
}
func (o *nonWRPResponseWriter) WriteWRPBytes(_ wrp.Format, _ []byte) (int, error) {
return 0, nil
}
func (o *nonWRPResponseWriter) WRPFormat() wrp.Format {
return wrp.Msgpack
}
// nonWRPResponseWriterFactory helps configure the WRP handler to fulfill scytale's use case of only consuming
// WRP requests but not produce WRP responses
func nonWRPResponseWriterFactory(w http.ResponseWriter, _ *wrphttp.Request) (wrphttp.ResponseWriter, error) {
return &nonWRPResponseWriter{
ResponseWriter: w,
}, nil
}
func newWRPFanoutHandler(fanoutHandler http.Handler) wrphttp.HandlerFunc {
if fanoutHandler == nil {
panic("fanoutHandler must be defined")
}
return func(w wrphttp.ResponseWriter, r *wrphttp.Request) {
fanoutPrep(r.Original, r.Entity.Bytes, r.Entity)
fanoutHandler.ServeHTTP(w, r.Original)
}
}
func newWRPFanoutHandlerWithPIDCheck(fanoutHandler http.Handler, p wrpAccessAuthority) wrphttp.HandlerFunc {
if fanoutHandler == nil || p == nil {
panic("fanoutHandler and partnersAuthority arguments must be defined")
}
encodeError := gokithttp.DefaultErrorEncoder
return func(w wrphttp.ResponseWriter, r *wrphttp.Request) {
var (
ctx = r.Context()
entity = r.Entity
fanout = r.Original
fanoutBody = r.Entity.Bytes
)
_, decoded := wrpcontext.GetMessage(ctx)
modified, err := p.authorizeWRP(ctx, &entity.Message)
if err != nil {
encodeError(ctx, err, w)
return
}
if modified || decoded {
if err := wrp.NewEncoderBytes(&fanoutBody, entity.Format).Encode(entity.Message); err != nil {
encodeError(ctx, err, w)
return
}
}
fanoutPrep(fanout, fanoutBody, entity)
fanoutHandler.ServeHTTP(w, fanout)
}
}
func fanoutPrep(fanout *http.Request, fanoutBody []byte, entity *wrphttp.Entity) {
fanout.Body, fanout.GetBody = xhttp.NewRewindBytes(fanoutBody)
fanout.ContentLength = int64(len(fanoutBody))
fanout.Header.Set("Content-Type", entity.Format.ContentType())
fanout.Header.Set("X-Webpa-Device-Name", entity.Message.Destination)
}