1
0
Fork 0
miniflux/http/client/client.go

238 lines
6.1 KiB
Go
Raw Normal View History

2018-04-28 13:51:07 -04:00
// Copyright 2018 Frédéric Guillot. All rights reserved.
2017-11-20 00:10:04 -05:00
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
2018-08-25 00:51:50 -04:00
package client // import "miniflux.app/http/client"
2017-11-20 00:10:04 -05:00
import (
2017-12-18 23:52:46 -05:00
"bytes"
2017-11-20 00:10:04 -05:00
"crypto/tls"
2018-02-08 21:16:54 -05:00
"crypto/x509"
2017-12-18 23:52:46 -05:00
"encoding/json"
2017-11-20 00:10:04 -05:00
"fmt"
2017-12-18 23:52:46 -05:00
"io"
"io/ioutil"
2018-02-08 21:16:54 -05:00
"net"
2017-11-20 00:10:04 -05:00
"net/http"
"net/url"
2017-12-18 23:52:46 -05:00
"strings"
2017-11-20 00:10:04 -05:00
"time"
2018-08-25 00:51:50 -04:00
"miniflux.app/errors"
"miniflux.app/logger"
"miniflux.app/timer"
"miniflux.app/version"
2017-11-20 00:10:04 -05:00
)
2018-02-08 21:16:54 -05: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 00:10:04 -05:00
// Client is a HTTP Client :)
type Client struct {
2017-12-18 23:52:46 -05:00
url string
etagHeader string
lastModifiedHeader string
authorizationHeader string
username string
password string
Insecure bool
2017-11-20 00:10:04 -05:00
}
2018-04-28 13:51:07 -04:00
// WithCredentials defines the username/password for HTTP Basic authentication.
func (c *Client) WithCredentials(username, password string) *Client {
if username != "" && password != "" {
c.username = username
c.password = password
}
2018-04-28 13:51:07 -04:00
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-02 22:32:14 -05:00
func (c *Client) Get() (*Response, error) {
2017-12-18 23:52:46 -05: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-02 22:15:08 -05:00
defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[HttpClient] url=%s", c.url))
2017-12-18 23:52:46 -05:00
2017-12-02 22:32:14 -05:00
client := c.buildClient()
2017-12-18 23:52:46 -05:00
resp, err := client.Do(request)
if resp != nil {
defer resp.Body.Close()
}
2017-11-20 00:10:04 -05:00
if err != nil {
2018-02-08 21:16:54 -05: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 00:10:04 -05:00
return nil, err
}
2018-01-02 21:30:26 -05: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 00:10:04 -05:00
}
logger.Debug("[HttpClient:%s] URL=%s, EffectiveURL=%s, Code=%d, Length=%d, Type=%s, ETag=%s, LastMod=%s, Expires=%s, Auth=%v",
2017-12-18 23:52:46 -05:00
request.Method,
c.url,
response.EffectiveURL,
response.StatusCode,
2018-01-02 21:30:26 -05:00
resp.ContentLength,
response.ContentType,
response.ETag,
response.LastModified,
resp.Header.Get("Expires"),
c.username != "",
2017-11-20 00:10:04 -05: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 00:10:04 -05:00
return response, err
}
2017-12-18 23:52:46 -05: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-02 22:32:14 -05:00
}
2018-02-25 14:49:08 -05:00
request.Header = c.buildHeaders()
2017-12-02 22:32:14 -05:00
if c.username != "" && c.password != "" {
request.SetBasicAuth(c.username, c.password)
}
2017-12-18 23:52:46 -05:00
return request, nil
2017-12-02 22:32:14 -05:00
}
func (c *Client) buildClient() http.Client {
2017-11-20 22:44:28 -05:00
client := http.Client{Timeout: time.Duration(requestTimeout * time.Second)}
2017-12-02 22:32:14 -05:00
if c.Insecure {
2017-11-20 22:44:28 -05:00
client.Transport = &http.Transport{
2017-11-20 00:10:04 -05:00
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
2017-11-20 22:44:28 -05:00
return client
2017-11-20 00:10:04 -05:00
}
2017-12-02 22:32:14 -05:00
func (c *Client) buildHeaders() http.Header {
2017-11-20 00:10:04 -05:00
headers := make(http.Header)
2018-07-28 13:32:48 -04:00
headers.Add("User-Agent", "Mozilla/5.0 (compatible; Miniflux/"+version.Version+"; +https://miniflux.app)")
headers.Add("Accept", "*/*")
2017-11-20 00:10:04 -05:00
2017-12-02 22:32:14 -05:00
if c.etagHeader != "" {
headers.Add("If-None-Match", c.etagHeader)
2017-11-20 00:10:04 -05:00
}
2017-12-02 22:32:14 -05:00
if c.lastModifiedHeader != "" {
headers.Add("If-Modified-Since", c.lastModifiedHeader)
2017-11-20 00:10:04 -05:00
}
2017-12-18 23:52:46 -05:00
if c.authorizationHeader != "" {
headers.Add("Authorization", c.authorizationHeader)
}
2018-06-19 23:21:24 -04:00
headers.Add("Connection", "close")
2017-11-20 00:10:04 -05:00
return headers
}
2018-04-28 13:51:07 -04:00
// New returns a new HTTP client.
func New(url string) *Client {
return &Client{url: url, Insecure: false}
2017-11-20 00:10:04 -05:00
}