-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
81 lines (73 loc) · 2.35 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
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
package wstf
import (
"encoding/json"
"errors"
"net/http"
)
// @see http://eagain.net/articles/go-dynamic-json/
// @see json.RawMessage
type Request struct {
// Link to Connection.
Connection *Connection `json:"-"`
// Shortcut for Connection.HttpRequest
HttpRequest *http.Request `json:"-"`
// The following fields are unmarshal-led from json string from client.
// The request unique ID.
Id string `json:"id"`
// HTTP Method.
Method string `json:"method"`
// Non-empty path.
Path string `json:"path"`
// Params matched from path.
Params map[string]string `json:"params"`
// The query part of request which is a JSON object and usually typed as map[string]string.
Query json.RawMessage `json:"query"`
// Headers of the request.
Headers map[string]string `json:"headers"`
// The request body of request, a JSON object.
Body json.RawMessage `json:"body"`
}
// The json.RawMessage type is used for some fields(Query & Body) of request
// to store the original partial json bytes and delay JSON decoding.
func NewRequest(jsonBytes []byte, connection *Connection) (*Request, error) {
var req *Request
err := json.Unmarshal(jsonBytes, &req)
if err != nil {
return nil, err
}
if !req.IsRequestValid() {
return nil, errors.New("expected fields is empty")
}
req.Params = make(map[string]string)
if connection != nil {
req.Connection = connection
req.HttpRequest = connection.HttpRequest
}
return req, err
}
// Is the request valid.
func (m *Request) IsRequestValid() bool {
return !(m.Id == "" || m.Method == "" || m.Path == "")
}
// Unmarshal the request.Query into a given struct.
// The obj should be pointer of some struct.
func (m *Request) UnmarshalQuery(obj interface{}) error {
return json.Unmarshal(m.Query, obj)
}
// Unmarshal the request.Body into a given struct.
// The obj should be pointer of some struct.
func (m *Request) UnmarshalBody(obj interface{}) error {
return json.Unmarshal(m.Body, obj)
}
// Get the query unmarshaller.
func (m *Request) GetQueryUnmarshaller() (*StructUnmarshaller, error) {
unmarshaller := &StructUnmarshaller{}
return unmarshaller, json.Unmarshal(m.Query, &unmarshaller.DataMap)
}
// Get the body unmarshaller.
func (m *Request) GetBodyUnmarshaller() (*StructUnmarshaller, error) {
unmarshaller := &StructUnmarshaller{
RawMessage: m.Body,
}
return unmarshaller, json.Unmarshal(m.Body, &unmarshaller.DataMap)
}