-
Notifications
You must be signed in to change notification settings - Fork 5
/
request.go
79 lines (70 loc) · 1.74 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
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
package requests
import (
"bytes"
"github.com/parallaxsecond/parsec-client-go/interface/auth"
"google.golang.org/protobuf/proto"
)
const requestHeaderSize uint16 = 30
// RequestBody represents a marshaled request body
type RequestBody struct {
*bytes.Buffer
}
// Request represents a Parsec request
type Request struct {
Header wireHeader
Body RequestBody
Auth auth.RequestAuthToken
}
// NewRequest creates a new request based on the opcode and the message.
func NewRequest(op OpCode, bdy proto.Message, authenticator auth.Authenticator, provider ProviderID) (*Request, error) {
bodyBuf, err := proto.Marshal(bdy)
if err != nil {
return nil, err
}
authtok, err := authenticator.NewRequestAuth()
if err != nil {
return nil, err
}
r := &Request{
Header: wireHeader{
versionMajor: versionMajorOne,
versionMinor: versionMinorZero,
flags: flagsZero,
provider: provider,
// todo set session handles
contentType: contentTypeProtobuf,
authType: authtok.AuthType(),
bodyLen: uint32(len(bodyBuf)),
authLen: uint16(authtok.Buffer().Len()),
opCode: op,
Status: StatusSuccess,
},
Body: RequestBody{
bytes.NewBuffer(bodyBuf),
},
Auth: authtok,
}
return r, nil
}
// Pack encodes a request to the wire format
func (r *Request) Pack() (*bytes.Buffer, error) {
if err := r.Header.checkForRequest(); err != nil {
return nil, err
}
b := bytes.NewBuffer([]byte{})
err := r.Header.pack(b)
if err != nil {
return nil, err
}
_, err = b.Write(r.Body.Bytes())
if err != nil {
return nil, err
}
_, err = b.Write(r.Auth.Buffer().Bytes())
if err != nil {
return nil, err
}
return b, nil
}