transport.go 3.15 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
// NewHTTPTransport returns a new HTTPTransport.
29
30
31
32
33
34
35
36
37
38
39
40
41
func NewHTTPTransport(serverURL string) *HTTPTransport {
	url := serverURL
	if !strings.HasSuffix(url, "/") {
		url += "/"
	}
	return &HTTPTransport{
		Server: url,
		client: &http.Client{
			Timeout: time.Second * 5,
		},
	}
}

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

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

	req, err := http.NewRequest(method, transport.Server+url, reader)
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
69
		return &Error{error: err, ErrorCode: ErrorTransport}
70
71
72
73
	}

	req.Header.Set("User-Agent", "irmago")
	if object != nil {
74
75
76
77
78
		if isstr {
			req.Header.Set("Content-Type", "text/plain; charset=UTF-8")
		} else {
			req.Header.Set("Content-Type", "application/json; charset=UTF-8")
		}
79
80
81
82
	}

	res, err := transport.client.Do(req)
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
83
		return &Error{error: err, ErrorCode: ErrorTransport}
84
85
86
87
	}

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

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

	return nil
}

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

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

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