aboutsummaryrefslogtreecommitdiffhomepage
path: root/http/client/response.go
blob: c084824e7b1541e144f8cf3ea82505e1c8185ee4 (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
// Copyright 2017 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/http/client"

import (
	"io"
	"io/ioutil"
	"mime"
	"strings"

	"golang.org/x/net/html/charset"
	"miniflux.app/logger"
)

// Response wraps a server response.
type Response struct {
	Body          io.Reader
	StatusCode    int
	EffectiveURL  string
	LastModified  string
	ETag          string
	ContentType   string
	ContentLength int64
}

// IsNotFound returns true if the resource doesn't exists anymore.
func (r *Response) IsNotFound() bool {
	return r.StatusCode == 404 || r.StatusCode == 410
}

// IsNotAuthorized returns true if the resource require authentication.
func (r *Response) IsNotAuthorized() bool {
	return r.StatusCode == 401
}

// HasServerFailure returns true if the status code represents a failure.
func (r *Response) HasServerFailure() bool {
	return r.StatusCode >= 400
}

// IsModified returns true if the resource has been modified.
func (r *Response) IsModified(etag, lastModified string) bool {
	if r.StatusCode == 304 {
		return false
	}

	if r.ETag != "" && r.ETag == etag {
		return false
	}

	if r.LastModified != "" && r.LastModified == lastModified {
		return false
	}

	return true
}

// EnsureUnicodeBody makes sure the body is encoded in UTF-8.
//
// If a charset other than UTF-8 is detected, we convert the document to UTF-8.
// This is used by the scraper and feed readers.
//
// Do not forget edge cases:
// - Some non-utf8 feeds specify encoding only in Content-Type, not in XML document.
func (r *Response) EnsureUnicodeBody() error {
	_, params, err := mime.ParseMediaType(r.ContentType)
	if err == nil {
		if enc, found := params["charset"]; found {
			enc = strings.ToLower(enc)
			if enc != "utf-8" && enc != "utf8" && enc != "" {
				logger.Debug("[EnsureUnicodeBody] Convert body to utf-8 from %s", enc)
				r.Body, err = charset.NewReader(r.Body, r.ContentType)
				if err != nil {
					return err
				}
			}
		}
	}
	return nil
}

// String returns the response body as string.
func (r *Response) String() string {
	bytes, _ := ioutil.ReadAll(r.Body)
	return string(bytes)
}