transport.go 2.85 KB
Newer Older
1
2
3
4
5
package protocol

import (
	"bytes"
	"encoding/json"
Sietse Ringers's avatar
Sietse Ringers committed
6
	"fmt"
7
8
9
10
11
12
13
14
15
16
17
18
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

type HTTPTransport struct {
	Server string
	client *http.Client
}

19
20
type ApiError struct {
	Status      int    `json:"status"`
21
	ErrorName   string `json:"error"`
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
	Description string `json:"description"`
	Message     string `json:"message"`
	Stacktrace  string `json:"stacktrace"`
}

type TransportError struct {
	Err    string
	Status int
	ApiErr *ApiError
}

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

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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")
	}

58
	var isstr bool
59
60
	var reader io.Reader
	if object != nil {
61
62
63
64
65
66
67
68
		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()}
			}
Sietse Ringers's avatar
Sietse Ringers committed
69
			fmt.Printf("POST: %s\n", string(marshaled))
70
			reader = bytes.NewBuffer(marshaled)
71
72
73
74
75
		}
	}

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

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

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

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

Sietse Ringers's avatar
Sietse Ringers committed
107
	fmt.Printf("RESPONSE: %s\n", string(body))
108
109
	err = json.Unmarshal(body, result)
	if err != nil {
110
		return &TransportError{Err: err.Error(), Status: res.StatusCode}
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
	}

	return nil
}

func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
	return transport.request(url, http.MethodPost, result, object)
}

func (transport *HTTPTransport) Get(url string, result interface{}) error {
	return transport.request(url, http.MethodGet, result, nil)
}

func (transport *HTTPTransport) Delete(url string) {
	// TODO
}