-
Notifications
You must be signed in to change notification settings - Fork 115
/
perform_handler_with_json.go
84 lines (65 loc) · 2.33 KB
/
perform_handler_with_json.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
package handler
import (
"encoding/json"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
)
const (
mbusHandlerLogTag = "MBus Handler"
responseMaxLengthErrMsg = "Response exceeded maximum allowed length"
UnlimitedResponseLength = -1
)
func PerformHandlerWithJSON(rawJSON []byte, handler Func, maxResponseLength int, logger boshlog.Logger) ([]byte, Request, error) {
var request Request
err := json.Unmarshal(rawJSON, &request)
if err != nil {
return []byte{}, request, bosherr.WrapError(err, "Unmarshalling JSON payload")
}
request.Payload = rawJSON
response := handler(request)
if response == nil {
logger.Info(mbusHandlerLogTag, "Nil response returned from handler")
return []byte{}, request, nil
}
respJSON, err := marshalResponse(response, maxResponseLength, logger)
if err != nil {
return respJSON, request, err
}
logger.Info(mbusHandlerLogTag, "Responding")
logger.DebugWithDetails(mbusHandlerLogTag, "Payload", respJSON)
return respJSON, request, nil
}
func BuildErrorWithJSON(msg string, logger boshlog.Logger) ([]byte, error) {
response := NewExceptionResponse(bosherr.Error(msg))
respJSON, err := json.Marshal(response)
if err != nil {
return respJSON, bosherr.WrapError(err, "Marshalling JSON")
}
logger.Info(mbusHandlerLogTag, "Building error", msg)
return respJSON, nil
}
func marshalResponse(response Response, maxResponseLength int, logger boshlog.Logger) ([]byte, error) {
respJSON, err := json.Marshal(response)
if err != nil {
logger.Error(mbusHandlerLogTag, "Failed to marshal response: %s", err.Error())
return respJSON, bosherr.WrapError(err, "Marshalling JSON response")
}
if maxResponseLength == UnlimitedResponseLength {
return respJSON, nil
}
if len(respJSON) > maxResponseLength {
respJSON, err = json.Marshal(response.Shorten())
if err != nil {
logger.Error(mbusHandlerLogTag, "Failed to marshal response: %s", err.Error())
return respJSON, bosherr.WrapError(err, "Marshalling JSON response")
}
}
if len(respJSON) > maxResponseLength {
respJSON, err = BuildErrorWithJSON(responseMaxLengthErrMsg, logger)
if err != nil {
logger.Error(mbusHandlerLogTag, "Failed to build 'max length exceeded' response: %s", err.Error())
return respJSON, bosherr.WrapError(err, "Building error")
}
}
return respJSON, nil
}