-
Notifications
You must be signed in to change notification settings - Fork 2
/
request.go
50 lines (39 loc) · 1.11 KB
/
request.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
package req
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"github.com/dpb587/ssoca/auth"
apierr "github.com/dpb587/ssoca/server/api/errors"
"github.com/sirupsen/logrus"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
)
type Request struct {
ID string
LoggerContext logrus.Fields
AuthToken *auth.Token
RawRequest *http.Request
RawResponse http.ResponseWriter
}
func (r *Request) ReadPayload(data interface{}) error {
bytes, err := ioutil.ReadAll(r.RawRequest.Body)
if err != nil {
return bosherr.WrapError(err, "Reading request body")
}
err = json.Unmarshal(bytes, data)
if err != nil {
return apierr.NewError(apierr.WrapError(err, "Unmarshaling request payload"), http.StatusBadRequest, "Invalid body")
}
return nil
}
func (r *Request) WritePayload(data interface{}) error {
bytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
return bosherr.WrapError(err, "Marshalling response payload")
}
r.RawResponse.Header().Add("Content-Type", "application/json")
io.WriteString(r.RawResponse, string(bytes))
io.WriteString(r.RawResponse, "\n")
return nil
}