aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/request.go
blob: adeda71b7ff7dc4e5eb32f0a9210397a6ac8a078 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// Copyright 2018 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.

package client // import "miniflux.app/client"

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"time"
)

const (
	userAgent      = "Miniflux Client Library"
	defaultTimeout = 80
)

// List of exposed errors.
var (
	ErrNotAuthorized = errors.New("miniflux: unauthorized (bad credentials)")
	ErrForbidden     = errors.New("miniflux: access forbidden")
	ErrServerError   = errors.New("miniflux: internal server error")
	ErrNotFound      = errors.New("miniflux: resource not found")
)

type errorResponse struct {
	ErrorMessage string `json:"error_message"`
}

type request struct {
	endpoint string
	username string
	password string
}

func (r *request) Get(path string) (io.ReadCloser, error) {
	return r.execute(http.MethodGet, path, nil)
}

func (r *request) Post(path string, data interface{}) (io.ReadCloser, error) {
	return r.execute(http.MethodPost, path, data)
}

func (r *request) PostFile(path string, f io.ReadCloser) (io.ReadCloser, error) {
	return r.execute(http.MethodPost, path, f)
}

func (r *request) Put(path string, data interface{}) (io.ReadCloser, error) {
	return r.execute(http.MethodPut, path, data)
}

func (r *request) Delete(path string) (io.ReadCloser, error) {
	return r.execute(http.MethodDelete, path, nil)
}

func (r *request) execute(method, path string, data interface{}) (io.ReadCloser, error) {
	if r.endpoint[len(r.endpoint)-1:] == "/" {
		r.endpoint = r.endpoint[:len(r.endpoint)-1]
	}

	u, err := url.Parse(r.endpoint + path)
	if err != nil {
		return nil, err
	}

	request := &http.Request{
		URL:    u,
		Method: method,
		Header: r.buildHeaders(),
	}
	request.SetBasicAuth(r.username, r.password)

	if data != nil {
		switch data.(type) {
		case io.ReadCloser:
			request.Body = data.(io.ReadCloser)
		default:
			request.Body = ioutil.NopCloser(bytes.NewBuffer(r.toJSON(data)))
		}
	}

	client := r.buildClient()
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}

	switch response.StatusCode {
	case http.StatusUnauthorized:
		return nil, ErrNotAuthorized
	case http.StatusForbidden:
		return nil, ErrForbidden
	case http.StatusInternalServerError:
		return nil, ErrServerError
	case http.StatusNotFound:
		return nil, ErrNotFound
	case http.StatusBadRequest:
		defer response.Body.Close()

		var resp errorResponse
		decoder := json.NewDecoder(response.Body)
		if err := decoder.Decode(&resp); err != nil {
			return nil, fmt.Errorf("miniflux: bad request error (%v)", err)
		}

		return nil, fmt.Errorf("miniflux: bad request (%s)", resp.ErrorMessage)
	}

	if response.StatusCode > 400 {
		return nil, fmt.Errorf("miniflux: status code=%d", response.StatusCode)
	}

	return response.Body, nil
}

func (r *request) buildClient() http.Client {
	return http.Client{
		Timeout: time.Duration(defaultTimeout * time.Second),
	}
}

func (r *request) buildHeaders() http.Header {
	headers := make(http.Header)
	headers.Add("User-Agent", userAgent)
	headers.Add("Content-Type", "application/json")
	headers.Add("Accept", "application/json")
	return headers
}

func (r *request) toJSON(v interface{}) []byte {
	b, err := json.Marshal(v)
	if err != nil {
		log.Println("Unable to convert interface to JSON:", err)
		return []byte("")
	}

	return b
}