-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.go
109 lines (94 loc) · 2.36 KB
/
data.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package jsonapi
import (
"context"
"encoding/json"
"net/http"
)
// Request represents most used data a handler need
type Request interface {
// Decode() helps you to read parameters in request body
Decode(interface{}) error
// R() retrieves original http request
R() *http.Request
// W() retrieves original http response writer
W() http.ResponseWriter
// WithValue() adds a new key-value pair in context of http request
WithValue(key, val interface{}) Request
}
// FakeRequest implements a Request and let you do some magic in it
type FakeRequest struct {
// this is used to implement Request.Decode()
Decoder *json.Decoder
// this is used to implement Request.R() and Request.WithValue()
Req *http.Request
// this is used to implement Request.W()
Resp http.ResponseWriter
}
// Decode implements Request
func (r *FakeRequest) Decode(data interface{}) error {
return r.Decoder.Decode(data)
}
// R implements Request
func (r *FakeRequest) R() *http.Request {
return r.Req
}
// W implements Request
func (r *FakeRequest) W() http.ResponseWriter {
return r.Resp
}
// WithValue implements Request
func (r *FakeRequest) WithValue(key, val interface{}) (ret Request) {
req := r.Req
req = req.WithContext(
context.WithValue(
req.Context(),
key,
val,
),
)
return &FakeRequest{
Decoder: r.Decoder,
Req: req,
Resp: r.Resp,
}
}
// FromHTTP creates a Request instance from http request and response
func FromHTTP(w http.ResponseWriter, r *http.Request) Request {
dec := json.NewDecoder(r.Body)
return &FakeRequest{
Decoder: dec,
Req: r,
Resp: w,
}
}
type reqWrapper struct {
Request
req *http.Request
}
func (r *reqWrapper) R() *http.Request {
return r.req
}
// WrapRequest creates a new Request, with http request replaced
func WrapRequest(q Request, r *http.Request) Request {
return &reqWrapper{
Request: q,
req: r,
}
}
type respWrapper struct {
Request
resp http.ResponseWriter
}
func (r *respWrapper) W() http.ResponseWriter {
return r.resp
}
// WrapResponse creates a new Request, with http response replaced
func WrapResponse(q Request, w http.ResponseWriter) Request {
return &respWrapper{
Request: q,
resp: w,
}
}