transport.go 3.27 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
package protocol

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

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

Sietse Ringers's avatar
Sietse Ringers committed
19
// ApiError is an error message returned by the API server on errors.
20
21
type ApiError struct {
	Status      int    `json:"status"`
22
	ErrorName   string `json:"error"`
23
24
25
26
27
	Description string `json:"description"`
	Message     string `json:"message"`
	Stacktrace  string `json:"stacktrace"`
}

Sietse Ringers's avatar
Sietse Ringers committed
28
// TransportError is an error occuring during HTTP traffic.
29
30
31
32
33
34
35
36
37
38
type TransportError struct {
	Err    string
	Status int
	ApiErr *ApiError
}

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

Sietse Ringers's avatar
Sietse Ringers committed
39
// NewHTTPTransport returns a new HTTPTransport.
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")
	}

61
	var isstr bool
62
63
	var reader io.Reader
	if object != nil {
64
65
66
67
68
69
70
71
		var objstr string
		if objstr, isstr = object.(string); isstr {
			reader = bytes.NewBuffer([]byte(objstr))
		} else {
			marshaled, err := json.Marshal(object)
			if err != nil {
				return &TransportError{Err: err.Error()}
			}
72
			//fmt.Printf("POST: %s\n", string(marshaled))
73
			reader = bytes.NewBuffer(marshaled)
74
75
76
77
78
		}
	}

	req, err := http.NewRequest(method, transport.Server+url, reader)
	if err != nil {
79
		return &TransportError{Err: err.Error()}
80
81
82
83
	}

	req.Header.Set("User-Agent", "irmago")
	if object != nil {
84
85
86
87
88
		if isstr {
			req.Header.Set("Content-Type", "text/plain; charset=UTF-8")
		} else {
			req.Header.Set("Content-Type", "application/json; charset=UTF-8")
		}
89
90
91
92
	}

	res, err := transport.client.Do(req)
	if err != nil {
93
		return &TransportError{Err: err.Error()}
94
95
96
97
	}

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
98
99
100
101
102
103
		return &TransportError{Err: err.Error(), Status: res.StatusCode}
	}
	if res.StatusCode != 200 {
		apierr := &ApiError{}
		json.Unmarshal(body, apierr)
		if apierr.ErrorName == "" { // Not an ApiErrorMessage
104
			return &TransportError{Status: res.StatusCode}
105
		}
106
		//fmt.Printf("ERROR: %+v\n", apierr)
107
		return &TransportError{Err: apierr.ErrorName, Status: res.StatusCode, ApiErr: apierr}
108
109
	}

110
	//fmt.Printf("RESPONSE: %s\n", string(body))
111
112
	err = json.Unmarshal(body, result)
	if err != nil {
113
		return &TransportError{Err: err.Error(), Status: res.StatusCode}
114
115
116
117
118
	}

	return nil
}

Sietse Ringers's avatar
Sietse Ringers committed
119
// Post sends the object to the server and parses its response into result.
120
121
122
123
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
	return transport.request(url, http.MethodPost, result, object)
}

Sietse Ringers's avatar
Sietse Ringers committed
124
// Get performs a GET request and parses the server's response into result.
125
126
127
128
func (transport *HTTPTransport) Get(url string, result interface{}) error {
	return transport.request(url, http.MethodGet, result, nil)
}

Sietse Ringers's avatar
Sietse Ringers committed
129
// Delete performs a DELETE.
130
131
132
func (transport *HTTPTransport) Delete(url string) {
	// TODO
}