1
0
mirror of https://git.sr.ht/~adnano/go-gemini synced 2024-11-10 00:32:11 +01:00
go-gemini/gemini.go

64 lines
1.8 KiB
Go
Raw Normal View History

2020-10-24 21:15:32 +02:00
package gemini
2020-09-26 01:09:49 +02:00
2020-09-26 22:52:14 +02:00
import (
"crypto/tls"
2020-09-26 22:52:14 +02:00
"crypto/x509"
2020-10-14 02:10:04 +02:00
"errors"
2020-09-26 22:52:14 +02:00
"sync"
"time"
2020-09-26 22:52:14 +02:00
)
2020-10-28 00:21:33 +01:00
var crlf = []byte("\r\n")
2020-09-26 01:09:49 +02:00
2020-10-14 02:10:04 +02:00
// Errors.
var (
2020-10-24 21:15:32 +02: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 21:15:32 +02:00
ErrBodyNotAllowed = errors.New("gemini: response status code does not allow for body")
2020-10-14 02:10:04 +02:00
)
2020-10-28 00:21:33 +01:00
// DefaultClient is the default client. It is used by Get and Do.
2020-09-26 22:52:14 +02:00
//
2020-10-28 00:21:33 +01:00
// On the first request, DefaultClient loads the default list of known hosts.
2020-10-14 02:10:04 +02:00
var DefaultClient Client
2020-09-26 22:52:14 +02:00
2020-10-28 00:21:33 +01: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-28 04:15:36 +02:00
2020-09-26 22:52:14 +02:00
func init() {
2020-09-28 04:18:21 +02:00
DefaultClient.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error {
2020-10-28 00:21:33 +01:00
defaultClientOnce.Do(func() { knownHosts.LoadDefault() })
2020-09-28 04:18:21 +02:00
return knownHosts.Lookup(hostname, cert)
2020-09-26 22:52:14 +02:00
}
2020-10-12 22:34:52 +02:00
DefaultClient.GetCertificate = func(hostname string, store *CertificateStore) *tls.Certificate {
2020-10-12 05:48:18 +02:00
if cert, err := store.Lookup(hostname); err == nil {
return cert
}
duration := time.Hour
cert, err := NewCertificate(hostname, duration)
if err != nil {
return nil
}
2020-10-12 05:48:18 +02:00
store.Add(hostname, cert)
return &cert
}
2020-09-26 22:52:14 +02:00
}