miniflux/http/client/client.go

235 lines
6 KiB
Go
Raw Normal View History

2018-04-28 19:51:07 +02:00
// Copyright 2018 Frédéric Guillot. All rights reserved.
2017-11-20 06:10:04 +01:00
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
2018-04-28 19:51:07 +02:00
package client
2017-11-20 06:10:04 +01:00
import (
2017-12-19 05:52:46 +01:00
"bytes"
2017-11-20 06:10:04 +01:00
"crypto/tls"
2018-02-09 03:16:54 +01:00
"crypto/x509"
2017-12-19 05:52:46 +01:00
"encoding/json"
2017-11-20 06:10:04 +01:00
"fmt"
2017-12-19 05:52:46 +01:00
"io"
"io/ioutil"
2018-02-09 03:16:54 +01:00
"net"
2017-11-20 06:10:04 +01:00
"net/http"
"net/url"
2017-12-19 05:52:46 +01:00
"strings"
2017-11-20 06:10:04 +01:00
"time"
2018-02-09 03:16:54 +01:00
"github.com/miniflux/miniflux/errors"
2017-12-16 03:55:57 +01:00
"github.com/miniflux/miniflux/logger"
2018-01-03 04:15:08 +01:00
"github.com/miniflux/miniflux/timer"
2018-01-23 05:43:03 +01:00
"github.com/miniflux/miniflux/version"
2017-11-20 06:10:04 +01:00
)
2018-02-09 03:16:54 +01:00
const (
// 20 seconds max.
requestTimeout = 20
// 15MB max.
maxBodySize = 1024 * 1024 * 15
)
var (
errInvalidCertificate = "Invalid SSL certificate (original error: %q)"
errTemporaryNetworkOperation = "This website is temporarily unreachable (original error: %q)"
errPermanentNetworkOperation = "This website is permanently unreachable (original error: %q)"
errRequestTimeout = "Website unreachable, the request timed out after %d seconds"
)
2017-11-20 06:10:04 +01:00
// Client is a HTTP Client :)
type Client struct {
2017-12-19 05:52:46 +01:00
url string
etagHeader string
lastModifiedHeader string
authorizationHeader string
username string
password string
Insecure bool
2017-11-20 06:10:04 +01:00
}
2018-04-28 19:51:07 +02:00
// WithCredentials defines the username/password for HTTP Basic authentication.
func (c *Client) WithCredentials(username, password string) *Client {
c.username = username
c.password = password
return c
}
// WithAuthorization defines authorization header value.
func (c *Client) WithAuthorization(authorization string) *Client {
c.authorizationHeader = authorization
return c
}
// WithCacheHeaders defines caching headers.
func (c *Client) WithCacheHeaders(etagHeader, lastModifiedHeader string) *Client {
c.etagHeader = etagHeader
c.lastModifiedHeader = lastModifiedHeader
return c
}
// Get execute a GET HTTP request.
2017-12-03 04:32:14 +01:00
func (c *Client) Get() (*Response, error) {
2017-12-19 05:52:46 +01:00
request, err := c.buildRequest(http.MethodGet, nil)
if err != nil {
return nil, err
}
return c.executeRequest(request)
}
// PostForm execute a POST HTTP request with form values.
func (c *Client) PostForm(values url.Values) (*Response, error) {
request, err := c.buildRequest(http.MethodPost, strings.NewReader(values.Encode()))
if err != nil {
return nil, err
}
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
return c.executeRequest(request)
}
// PostJSON execute a POST HTTP request with JSON payload.
func (c *Client) PostJSON(data interface{}) (*Response, error) {
b, err := json.Marshal(data)
if err != nil {
return nil, err
}
request, err := c.buildRequest(http.MethodPost, bytes.NewReader(b))
if err != nil {
return nil, err
}
request.Header.Add("Content-Type", "application/json")
return c.executeRequest(request)
}
func (c *Client) executeRequest(request *http.Request) (*Response, error) {
2018-01-03 04:15:08 +01:00
defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[HttpClient] url=%s", c.url))
2017-12-19 05:52:46 +01:00
2017-12-03 04:32:14 +01:00
client := c.buildClient()
2017-12-19 05:52:46 +01:00
resp, err := client.Do(request)
if resp != nil {
defer resp.Body.Close()
}
2017-11-20 06:10:04 +01:00
if err != nil {
2018-02-09 03:16:54 +01:00
if uerr, ok := err.(*url.Error); ok {
switch uerr.Err.(type) {
case x509.CertificateInvalidError, x509.HostnameError:
err = errors.NewLocalizedError(errInvalidCertificate, uerr.Err)
case *net.OpError:
if uerr.Err.(*net.OpError).Temporary() {
err = errors.NewLocalizedError(errTemporaryNetworkOperation, uerr.Err)
} else {
err = errors.NewLocalizedError(errPermanentNetworkOperation, uerr.Err)
}
case net.Error:
nerr := uerr.Err.(net.Error)
if nerr.Timeout() {
err = errors.NewLocalizedError(errRequestTimeout, requestTimeout)
} else if nerr.Temporary() {
err = errors.NewLocalizedError(errTemporaryNetworkOperation, nerr)
}
}
}
2017-11-20 06:10:04 +01:00
return nil, err
}
2018-01-03 03:30:26 +01:00
if resp.ContentLength > maxBodySize {
return nil, fmt.Errorf("client: response too large (%d bytes)", resp.ContentLength)
}
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("client: error while reading body %v", err)
}
response := &Response{
Body: bytes.NewReader(buf),
StatusCode: resp.StatusCode,
EffectiveURL: resp.Request.URL.String(),
LastModified: resp.Header.Get("Last-Modified"),
ETag: resp.Header.Get("ETag"),
ContentType: resp.Header.Get("Content-Type"),
ContentLength: resp.ContentLength,
2017-11-20 06:10:04 +01:00
}
logger.Debug("[HttpClient:%s] URL=%s, EffectiveURL=%s, Code=%d, Length=%d, Type=%s, ETag=%s, LastMod=%s, Expires=%s",
2017-12-19 05:52:46 +01:00
request.Method,
c.url,
response.EffectiveURL,
response.StatusCode,
2018-01-03 03:30:26 +01:00
resp.ContentLength,
response.ContentType,
response.ETag,
response.LastModified,
resp.Header.Get("Expires"),
2017-11-20 06:10:04 +01:00
)
// Ignore caching headers for feeds that do not want any cache.
if resp.Header.Get("Expires") == "0" {
logger.Debug("[HttpClient] Ignore caching headers for %q", response.EffectiveURL)
response.ETag = ""
response.LastModified = ""
}
2017-11-20 06:10:04 +01:00
return response, err
}
2017-12-19 05:52:46 +01:00
func (c *Client) buildRequest(method string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequest(method, c.url, body)
if err != nil {
return nil, err
2017-12-03 04:32:14 +01:00
}
2018-02-25 20:49:08 +01:00
request.Header = c.buildHeaders()
2017-12-03 04:32:14 +01:00
if c.username != "" && c.password != "" {
request.SetBasicAuth(c.username, c.password)
}
2017-12-19 05:52:46 +01:00
return request, nil
2017-12-03 04:32:14 +01:00
}
func (c *Client) buildClient() http.Client {
2017-11-21 04:44:28 +01:00
client := http.Client{Timeout: time.Duration(requestTimeout * time.Second)}
2017-12-03 04:32:14 +01:00
if c.Insecure {
2017-11-21 04:44:28 +01:00
client.Transport = &http.Transport{
2017-11-20 06:10:04 +01:00
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
2017-11-21 04:44:28 +01:00
return client
2017-11-20 06:10:04 +01:00
}
2017-12-03 04:32:14 +01:00
func (c *Client) buildHeaders() http.Header {
2017-11-20 06:10:04 +01:00
headers := make(http.Header)
2018-01-23 05:43:03 +01:00
headers.Add("User-Agent", "Mozilla/5.0 (compatible; Miniflux/"+version.Version+"; +https://miniflux.net)")
headers.Add("Accept", "*/*")
2017-11-20 06:10:04 +01:00
2017-12-03 04:32:14 +01:00
if c.etagHeader != "" {
headers.Add("If-None-Match", c.etagHeader)
2017-11-20 06:10:04 +01:00
}
2017-12-03 04:32:14 +01:00
if c.lastModifiedHeader != "" {
headers.Add("If-Modified-Since", c.lastModifiedHeader)
2017-11-20 06:10:04 +01:00
}
2017-12-19 05:52:46 +01:00
if c.authorizationHeader != "" {
headers.Add("Authorization", c.authorizationHeader)
}
2018-06-20 05:21:24 +02:00
headers.Add("Connection", "close")
2017-11-20 06:10:04 +01:00
return headers
}
2018-04-28 19:51:07 +02:00
// New returns a new HTTP client.
func New(url string) *Client {
return &Client{url: url, Insecure: false}
2017-11-20 06:10:04 +01:00
}