-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathclient.go
70 lines (60 loc) · 1.49 KB
/
client.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
package rfc3161
import (
"bytes"
"encoding/asn1"
"errors"
"io/ioutil"
"net/http"
)
// Errors
var (
ErrRequestFailed = errors.New("rfc3161: client: Request failed")
)
// Client handles requests to an HTTP or websocket time-stamp-service
// You may override the underlying http client used by setting the HTTPClient field
type Client struct {
HTTPClient *http.Client
URL string
}
// NewClient creates a new rfc3161.Client given a URL.
func NewClient(url string) *Client {
client := new(Client)
client.HTTPClient = http.DefaultClient
client.URL = url
return client
}
// Do a time stamp request and get back the Time Stamp Response.
// This will not verify the response. It is the caller's responsibility
// to call resp.Verify() on the returned TimeStampResp.
func (client *Client) Do(tsq *TimeStampReq) (*TimeStampResp, error) {
der, err := asn1.Marshal(tsq)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", client.URL, bytes.NewBuffer(der))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/timestamp-query")
resp, err := client.HTTPClient.Do(req)
defer resp.Body.Close()
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
tsr := new(TimeStampResp)
rest, err := asn1.Unmarshal(body, tsr)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, ErrUnrecognizedData
}
if tsr.Status.Status.IsError() {
return tsr, &tsr.Status
}
return tsr, nil
}