transport.go 4.54 KB
Newer Older
1
package irmago
2
3
4
5

import (
	"bytes"
	"encoding/json"
6
	"fmt"
7
8
9
	"io"
	"io/ioutil"
	"net/http"
10
	"path/filepath"
11
12
13
14
	"strings"
	"time"
)

Sietse Ringers's avatar
Sietse Ringers committed
15
// HTTPTransport sends and receives JSON messages to a HTTP server.
16
type HTTPTransport struct {
Sietse Ringers's avatar
Sietse Ringers committed
17
18
19
	Server  string
	client  *http.Client
	headers map[string]string
20
21
}

22
const verbose = false
Sietse Ringers's avatar
Sietse Ringers committed
23

Sietse Ringers's avatar
Sietse Ringers committed
24
// NewHTTPTransport returns a new HTTPTransport.
25
26
func NewHTTPTransport(serverURL string) *HTTPTransport {
	url := serverURL
27
	if serverURL != "" && !strings.HasSuffix(url, "/") { // TODO fix this
28
29
30
		url += "/"
	}
	return &HTTPTransport{
Sietse Ringers's avatar
Sietse Ringers committed
31
32
		Server:  url,
		headers: map[string]string{},
33
		client: &http.Client{
Sietse Ringers's avatar
Sietse Ringers committed
34
			Timeout: time.Second * 15,
35
36
37
38
		},
	}
}

39
// SetHeader sets a header to be sent in requests.
Sietse Ringers's avatar
Sietse Ringers committed
40
41
42
43
func (transport *HTTPTransport) SetHeader(name, val string) {
	transport.headers[name] = val
}

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
func (transport *HTTPTransport) request(
	url string, method string, reader io.Reader, isstr bool,
) (response *http.Response, err error) {
	req, err := http.NewRequest(method, transport.Server+url, reader)
	if err != nil {
		return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
	}

	req.Header.Set("User-Agent", "irmago")
	if reader != nil {
		if isstr {
			req.Header.Set("Content-Type", "text/plain; charset=UTF-8")
		} else {
			req.Header.Set("Content-Type", "application/json; charset=UTF-8")
		}
	}
	for name, val := range transport.headers {
		req.Header.Set(name, val)
	}

	res, err := transport.client.Do(req)
	if err != nil {
		return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
	}
	return res, nil
}

func (transport *HTTPTransport) jsonRequest(url string, method string, result interface{}, object interface{}) error {
72
	if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
73
74
75
76
77
78
		panic("Unsupported HTTP method " + method)
	}
	if method == http.MethodGet && object != nil {
		panic("Cannot GET and also post an object")
	}

79
	var isstr bool
80
81
	var reader io.Reader
	if object != nil {
82
83
84
85
86
87
		var objstr string
		if objstr, isstr = object.(string); isstr {
			reader = bytes.NewBuffer([]byte(objstr))
		} else {
			marshaled, err := json.Marshal(object)
			if err != nil {
Tomas's avatar
Tomas committed
88
				return &SessionError{ErrorType: ErrorSerialization, Err: err}
89
			}
Sietse Ringers's avatar
Sietse Ringers committed
90
			if verbose {
91
				fmt.Printf("%s %s: %s\n", method, url, string(marshaled))
Sietse Ringers's avatar
Sietse Ringers committed
92
			}
93
			reader = bytes.NewBuffer(marshaled)
94
		}
95
96
97
98
	} else {
		if verbose {
			fmt.Printf("%s %s\n", method, url)
		}
99
100
	}

101
	res, err := transport.request(url, method, reader, isstr)
102
	if err != nil {
103
		return err
104
	}
105
106
107
108
	if method == http.MethodDelete {
		return nil
	}

109
110
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
111
		return &SessionError{ErrorType: ErrorServerResponse, Err: err, Status: res.StatusCode}
112
113
114
	}
	if res.StatusCode != 200 {
		apierr := &ApiError{}
Sietse Ringers's avatar
Sietse Ringers committed
115
116
		err = json.Unmarshal(body, apierr)
		if err != nil || apierr.ErrorName == "" { // Not an ApiErrorMessage
Tomas's avatar
Tomas committed
117
			return &SessionError{ErrorType: ErrorServerResponse, Status: res.StatusCode}
118
		}
Sietse Ringers's avatar
Sietse Ringers committed
119
120
121
		if verbose {
			fmt.Printf("ERROR: %+v\n", apierr)
		}
Tomas's avatar
Tomas committed
122
		return &SessionError{ErrorType: ErrorApi, Status: res.StatusCode, ApiError: apierr}
123
124
	}

Sietse Ringers's avatar
Sietse Ringers committed
125
126
127
	if verbose {
		fmt.Printf("RESPONSE: %s\n", string(body))
	}
128
129
130
131
132
	if _, resultstr := result.(*string); resultstr {
		*result.(*string) = string(body)
	} else {
		err = json.Unmarshal(body, result)
		if err != nil {
Tomas's avatar
Tomas committed
133
			return &SessionError{ErrorType: ErrorServerResponse, Err: err, Status: res.StatusCode}
134
		}
135
136
137
138
139
	}

	return nil
}

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
func (transport *HTTPTransport) GetBytes(url string) ([]byte, error) {
	res, err := transport.request(url, http.MethodGet, nil, false)
	if err != nil {
		return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
	}
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, &SessionError{ErrorType: ErrorServerResponse, Err: err, Status: res.StatusCode}
	}
	return b, nil
}

func (transport *HTTPTransport) GetFile(url string, dest string) error {
	b, err := transport.GetBytes(url)
	if err != nil {
		return err
	}
	if err = ensureDirectoryExists(filepath.Dir(dest)); err != nil {
		return err
	}
	return saveFile(dest, b)
}

Sietse Ringers's avatar
Sietse Ringers committed
163
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
164
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
165
	return transport.jsonRequest(url, http.MethodPost, result, object)
166
167
}

Sietse Ringers's avatar
Sietse Ringers committed
168
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
169
func (transport *HTTPTransport) Get(url string, result interface{}) error {
170
	return transport.jsonRequest(url, http.MethodGet, result, nil)
171
172
}

Sietse Ringers's avatar
Sietse Ringers committed
173
// Delete performs a DELETE.
174
func (transport *HTTPTransport) Delete() {
175
	_ = transport.jsonRequest("", http.MethodDelete, nil, nil)
176
}