go-gemini/gemini.go

65 lines
1.9 KiB
Go
Raw Normal View History

2020-10-24 13:15:32 -06:00
package gemini
2020-09-25 17:09:49 -06:00
2020-09-26 14:52:14 -06:00
import (
"crypto/tls"
2020-09-26 14:52:14 -06:00
"crypto/x509"
2020-10-13 18:10:04 -06:00
"errors"
2020-09-26 14:52:14 -06:00
"sync"
"time"
2020-09-26 14:52:14 -06:00
)
2020-10-27 17:21:33 -06:00
var crlf = []byte("\r\n")
2020-09-25 17:09:49 -06:00
2020-10-13 18:10:04 -06:00
// Errors.
var (
2020-10-24 13:15:32 -06:00
ErrInvalidURL = errors.New("gemini: invalid URL")
ErrInvalidResponse = errors.New("gemini: invalid response")
ErrCertificateUnknown = errors.New("gemini: unknown certificate")
ErrCertificateExpired = errors.New("gemini: certificate expired")
ErrCertificateNotTrusted = errors.New("gemini: certificate is not trusted")
ErrNotAFile = errors.New("gemini: not a file")
ErrNotAGeminiURL = errors.New("gemini: not a Gemini URL")
2020-10-24 13:15:32 -06:00
ErrBodyNotAllowed = errors.New("gemini: response status code does not allow for body")
2020-10-27 20:12:10 -06:00
ErrTooManyRedirects = errors.New("gemini: too many redirects")
2020-10-13 18:10:04 -06:00
)
2020-10-27 17:21:33 -06:00
// DefaultClient is the default client. It is used by Get and Do.
2020-09-26 14:52:14 -06:00
//
2020-10-27 17:21:33 -06:00
// On the first request, DefaultClient loads the default list of known hosts.
2020-10-13 18:10:04 -06:00
var DefaultClient Client
2020-09-26 14:52:14 -06:00
2020-10-27 17:21:33 -06:00
// Get performs a Gemini request for the given url.
//
// Get is a wrapper around DefaultClient.Get.
func Get(url string) (*Response, error) {
return DefaultClient.Get(url)
}
// Do performs a Gemini request and returns a Gemini response.
//
// Do is a wrapper around DefaultClient.Do.
func Do(req *Request) (*Response, error) {
return DefaultClient.Do(req)
}
var defaultClientOnce sync.Once
2020-09-27 20:15:36 -06:00
2020-09-26 14:52:14 -06:00
func init() {
2020-09-27 20:18:21 -06:00
DefaultClient.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error {
2020-10-27 17:21:33 -06:00
defaultClientOnce.Do(func() { knownHosts.LoadDefault() })
2020-09-27 20:18:21 -06:00
return knownHosts.Lookup(hostname, cert)
2020-09-26 14:52:14 -06:00
}
DefaultClient.GetCertificate = func(req *Request, store *ClientCertificateStore) *tls.Certificate {
if cert, err := store.Lookup(req.URL.Hostname(), req.URL.Path); err == nil {
return cert
}
duration := time.Hour
cert, err := NewCertificate("", duration)
if err != nil {
return nil
}
store.Add(req.URL.Hostname()+req.URL.Path, cert)
return &cert
}
2020-09-26 14:52:14 -06:00
}