transport.go 3.12 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
}

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

Sietse Ringers's avatar
Sietse Ringers committed
36
37
38
39
func (transport *HTTPTransport) SetHeader(name, val string) {
	transport.headers[name] = val
}

Sietse Ringers's avatar
Sietse Ringers committed
40
func (transport *HTTPTransport) request(url string, method string, result interface{}, object interface{}) error {
41
42
43
44
45
46
47
	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")
	}

48
	var isstr bool
49
50
	var reader io.Reader
	if object != nil {
51
52
		var objstr string
		if objstr, isstr = object.(string); isstr {
Sietse Ringers's avatar
Sietse Ringers committed
53
			fmt.Printf("GET %s\n", url)
54
55
56
57
			reader = bytes.NewBuffer([]byte(objstr))
		} else {
			marshaled, err := json.Marshal(object)
			if err != nil {
58
				return &Error{Err: err, ErrorCode: ErrorSerialization}
Sietse Ringers's avatar
Sietse Ringers committed
59
				//return &TransportError{Err: err.Error()}
60
			}
Sietse Ringers's avatar
Sietse Ringers committed
61
			fmt.Printf("POST %s: %s\n", url, string(marshaled))
62
			reader = bytes.NewBuffer(marshaled)
63
64
65
66
67
		}
	}

	req, err := http.NewRequest(method, transport.Server+url, reader)
	if err != nil {
68
		return &Error{Err: err, ErrorCode: ErrorTransport}
69
70
71
72
	}

	req.Header.Set("User-Agent", "irmago")
	if object != nil {
73
74
75
76
77
		if isstr {
			req.Header.Set("Content-Type", "text/plain; charset=UTF-8")
		} else {
			req.Header.Set("Content-Type", "application/json; charset=UTF-8")
		}
78
	}
Sietse Ringers's avatar
Sietse Ringers committed
79
80
81
	for name, val := range transport.headers {
		req.Header.Set(name, val)
	}
82
83
84

	res, err := transport.client.Do(req)
	if err != nil {
85
		return &Error{Err: err, ErrorCode: ErrorTransport}
86
87
88
89
	}

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
90
		return &Error{Err: err, Status: res.StatusCode}
91
92
93
94
95
	}
	if res.StatusCode != 200 {
		apierr := &ApiError{}
		json.Unmarshal(body, apierr)
		if apierr.ErrorName == "" { // Not an ApiErrorMessage
Sietse Ringers's avatar
Sietse Ringers committed
96
			return &Error{ErrorCode: ErrorTransport, Status: res.StatusCode}
97
		}
Sietse Ringers's avatar
Sietse Ringers committed
98
		fmt.Printf("ERROR: %+v\n", apierr)
Sietse Ringers's avatar
Sietse Ringers committed
99
		return &Error{ErrorCode: ErrorTransport, Status: res.StatusCode, ApiError: apierr}
100
101
	}

Sietse Ringers's avatar
Sietse Ringers committed
102
	fmt.Printf("RESPONSE: %s\n", string(body))
103
104
	err = json.Unmarshal(body, result)
	if err != nil {
105
		return &Error{Err: err, Status: res.StatusCode}
106
107
108
109
110
	}

	return nil
}

Sietse Ringers's avatar
Sietse Ringers committed
111
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
112
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
113
114
115
	return transport.request(url, http.MethodPost, result, object)
}

Sietse Ringers's avatar
Sietse Ringers committed
116
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
117
func (transport *HTTPTransport) Get(url string, result interface{}) error {
118
119
120
	return transport.request(url, http.MethodGet, result, nil)
}

Sietse Ringers's avatar
Sietse Ringers committed
121
// Delete performs a DELETE.
122
123
124
func (transport *HTTPTransport) Delete(url string) {
	// TODO
}