transport.go 2.51 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package protocol

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

type HTTPTransport struct {
	Server string
	client *http.Client
}

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
type ApiError struct {
	Status      int    `json:"status"`
	ErrorName   string `json:"error"'`
	Description string `json:"description"`
	Message     string `json:"message"`
	Stacktrace  string `json:"stacktrace"`
}

type TransportError struct {
	Err    string
	Status int
	ApiErr *ApiError
}

func (te TransportError) Error() string {
	return te.Err
}

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
func NewHTTPTransport(serverURL string) *HTTPTransport {
	url := serverURL
	if !strings.HasSuffix(url, "/") {
		url += "/"
	}
	return &HTTPTransport{
		Server: url,
		client: &http.Client{
			Timeout: time.Second * 5,
		},
	}
}

func (transport *HTTPTransport) request(url string, method string, result interface{}, object interface{}) error {
	if method != http.MethodPost && method != http.MethodGet {
		panic("Unsupported HTTP method " + method)
	}
	if method == http.MethodGet && object != nil {
		panic("Cannot GET and also post an object")
	}

	var reader io.Reader
	if object != nil {
		marshaled, err := json.Marshal(object)
		if err != nil {
61
			return &TransportError{Err: err.Error()}
62
63
64
65
66
67
		}
		reader = bytes.NewBuffer(marshaled)
	}

	req, err := http.NewRequest(method, transport.Server+url, reader)
	if err != nil {
68
		return &TransportError{Err: err.Error()}
69
70
71
72
73
74
75
76
77
	}

	req.Header.Set("User-Agent", "irmago")
	if object != nil {
		req.Header.Set("Content-Type", "application/json; charset=UTF-8")
	}

	res, err := transport.client.Do(req)
	if err != nil {
78
		return &TransportError{Err: err.Error()}
79
80
81
82
	}

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
83
84
85
86
87
88
89
90
91
		return &TransportError{Err: err.Error(), Status: res.StatusCode}
	}
	if res.StatusCode != 200 {
		apierr := &ApiError{}
		json.Unmarshal(body, apierr)
		if apierr.ErrorName == "" { // Not an ApiErrorMessage
			return &TransportError{Err: err.Error(), Status: res.StatusCode}
		}
		return &TransportError{Err: apierr.ErrorName, Status: res.StatusCode, ApiErr: apierr}
92
93
94
95
	}

	err = json.Unmarshal(body, result)
	if err != nil {
96
		return &TransportError{Err: err.Error(), Status: res.StatusCode}
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
	}

	return nil
}

func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
	return transport.request(url, http.MethodPost, result, object)
}

func (transport *HTTPTransport) Get(url string, result interface{}) error {
	return transport.request(url, http.MethodGet, result, nil)
}

func (transport *HTTPTransport) Delete(url string) {
	// TODO
}