Implement Client connection timeout

This commit is contained in:
Adnan Maolood 2020-10-31 20:55:56 -04:00
parent a2fc1772bf
commit 42c95f8c8d
2 changed files with 23 additions and 1 deletions

View File

@ -8,6 +8,7 @@ import (
"net/url" "net/url"
"path" "path"
"strings" "strings"
"time"
) )
// Client is a Gemini client. // Client is a Gemini client.
@ -18,6 +19,14 @@ type Client struct {
// Certificates stores client-side certificates. // Certificates stores client-side certificates.
Certificates CertificateStore Certificates CertificateStore
// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time and reading
// the response body. The timer remains running after
// Get and Do return and will interrupt reading of the Response.Body.
//
// A Timeout of zero means no timeout.
Timeout time.Duration
// GetInput is called to retrieve input when the server requests it. // GetInput is called to retrieve input when the server requests it.
// If GetInput is nil or returns false, no input will be sent and // If GetInput is nil or returns false, no input will be sent and
// the response will be returned. // the response will be returned.
@ -56,6 +65,13 @@ func (c *Client) Do(req *Request) (*Response, error) {
return c.do(req, nil) return c.do(req, nil)
} }
func (c *Client) deadline() time.Time {
if c.Timeout > 0 {
return time.Now().Add(c.Timeout)
}
return time.Time{}
}
func (c *Client) do(req *Request, via []*Request) (*Response, error) { func (c *Client) do(req *Request, via []*Request) (*Response, error) {
// Connect to the host // Connect to the host
config := &tls.Config{ config := &tls.Config{
@ -72,7 +88,12 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
// TODO: Set connection deadline // Set connection deadline
if deadline := c.deadline(); !deadline.IsZero() {
if err := conn.SetDeadline(deadline); err != nil {
return nil, err
}
}
// Write the request // Write the request
w := bufio.NewWriter(conn) w := bufio.NewWriter(conn)

View File

@ -20,6 +20,7 @@ var (
) )
func init() { func init() {
client.Timeout = 2 * time.Minute
client.KnownHosts.LoadDefault() client.KnownHosts.LoadDefault()
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error { client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error {
err := knownHosts.Lookup(hostname, cert) err := knownHosts.Lookup(hostname, cert)