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

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

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

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

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

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

Sietse Ringers's avatar
Sietse Ringers committed
43
func (transport *HTTPTransport) request(url string, method string, result interface{}, object interface{}) error {
44
	if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
45
46
47
48
49
50
		panic("Unsupported HTTP method " + method)
	}
	if method == http.MethodGet && object != nil {
		panic("Cannot GET and also post an object")
	}

51
	var isstr bool
52
53
	var reader io.Reader
	if object != nil {
54
55
56
57
58
59
		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
60
				return &SessionError{ErrorType: ErrorSerialization, Err: err}
61
			}
Sietse Ringers's avatar
Sietse Ringers committed
62
			if verbose {
63
				fmt.Printf("%s %s: %s\n", method, url, string(marshaled))
Sietse Ringers's avatar
Sietse Ringers committed
64
			}
65
			reader = bytes.NewBuffer(marshaled)
66
		}
67
68
69
70
	} else {
		if verbose {
			fmt.Printf("%s %s\n", method, url)
		}
71
72
73
74
	}

	req, err := http.NewRequest(method, transport.Server+url, reader)
	if err != nil {
Tomas's avatar
Tomas committed
75
		return &SessionError{ErrorType: ErrorTransport, Err: err}
76
77
78
79
	}

	req.Header.Set("User-Agent", "irmago")
	if object != nil {
80
81
82
83
84
		if isstr {
			req.Header.Set("Content-Type", "text/plain; charset=UTF-8")
		} else {
			req.Header.Set("Content-Type", "application/json; charset=UTF-8")
		}
85
	}
Sietse Ringers's avatar
Sietse Ringers committed
86
87
88
	for name, val := range transport.headers {
		req.Header.Set(name, val)
	}
89
90
91

	res, err := transport.client.Do(req)
	if err != nil {
Tomas's avatar
Tomas committed
92
		return &SessionError{ErrorType: ErrorTransport, Err: err}
93
94
	}

95
96
97
98
	if method == http.MethodDelete {
		return nil
	}

99
100
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
101
		return &SessionError{ErrorType: ErrorServerResponse, Err: err, Status: res.StatusCode}
102
103
104
	}
	if res.StatusCode != 200 {
		apierr := &ApiError{}
Sietse Ringers's avatar
Sietse Ringers committed
105
106
		err = json.Unmarshal(body, apierr)
		if err != nil || apierr.ErrorName == "" { // Not an ApiErrorMessage
Tomas's avatar
Tomas committed
107
			return &SessionError{ErrorType: ErrorServerResponse, Status: res.StatusCode}
108
		}
Sietse Ringers's avatar
Sietse Ringers committed
109
110
111
		if verbose {
			fmt.Printf("ERROR: %+v\n", apierr)
		}
Tomas's avatar
Tomas committed
112
		return &SessionError{ErrorType: ErrorApi, Status: res.StatusCode, ApiError: apierr}
113
114
	}

Sietse Ringers's avatar
Sietse Ringers committed
115
116
117
	if verbose {
		fmt.Printf("RESPONSE: %s\n", string(body))
	}
118
119
120
121
122
	if _, resultstr := result.(*string); resultstr {
		*result.(*string) = string(body)
	} else {
		err = json.Unmarshal(body, result)
		if err != nil {
Tomas's avatar
Tomas committed
123
			return &SessionError{ErrorType: ErrorServerResponse, Err: err, Status: res.StatusCode}
124
		}
125
126
127
128
129
	}

	return nil
}

Sietse Ringers's avatar
Sietse Ringers committed
130
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
131
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
132
133
134
	return transport.request(url, http.MethodPost, result, object)
}

Sietse Ringers's avatar
Sietse Ringers committed
135
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
136
func (transport *HTTPTransport) Get(url string, result interface{}) error {
137
138
139
	return transport.request(url, http.MethodGet, result, nil)
}

Sietse Ringers's avatar
Sietse Ringers committed
140
// Delete performs a DELETE.
141
func (transport *HTTPTransport) Delete() {
Sietse Ringers's avatar
Sietse Ringers committed
142
	_ = transport.request("", http.MethodDelete, nil, nil)
143
}