aboutsummaryrefslogtreecommitdiffhomepage
path: root/reader/browser/browser.go
blob: 733d5f55c5d761f2006efd0ae4faae175de59f68 (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
// 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 browser // import "miniflux.app/reader/browser"

import (
	"miniflux.app/errors"
	"miniflux.app/http/client"
)

var (
	errRequestFailed    = "Unable to open this link: %v"
	errServerFailure    = "Unable to fetch this resource (Status Code = %d)"
	errEncoding         = "Unable to normalize encoding: %q"
	errEmptyFeed        = "This feed is empty"
	errResourceNotFound = "Resource not found (404), this feed doesn't exists anymore, check the feed URL"
	errNotAuthorized    = "You are not authorized to access this resource (invalid username/password)"
)

// Exec executes a HTTP request and handles errors.
func Exec(request *client.Client) (*client.Response, *errors.LocalizedError) {
	response, err := request.Get()
	if err != nil {
		if e, ok := err.(*errors.LocalizedError); ok {
			return nil, e
		}
		return nil, errors.NewLocalizedError(errRequestFailed, err)
	}

	if response.IsNotFound() {
		return nil, errors.NewLocalizedError(errResourceNotFound)
	}

	if response.IsNotAuthorized() {
		return nil, errors.NewLocalizedError(errNotAuthorized)
	}

	if response.HasServerFailure() {
		return nil, errors.NewLocalizedError(errServerFailure, response.StatusCode)
	}

	if response.StatusCode != 304 {
		// Content-Length = -1 when no Content-Length header is sent.
		if response.ContentLength == 0 {
			return nil, errors.NewLocalizedError(errEmptyFeed)
		}

		if err := response.EnsureUnicodeBody(); err != nil {
			return nil, errors.NewLocalizedError(errEncoding, err)
		}
	}

	return response, nil
}