summaryrefslogtreecommitdiff
path: root/gemini/client.go
diff options
context:
space:
mode:
Diffstat (limited to 'gemini/client.go')
-rw-r--r--gemini/client.go69
1 files changed, 69 insertions, 0 deletions
diff --git a/gemini/client.go b/gemini/client.go
new file mode 100644
index 0000000..53c8b71
--- /dev/null
+++ b/gemini/client.go
@@ -0,0 +1,69 @@
+package gemini
+
+import (
+ "bytes"
+ "crypto/tls"
+ "errors"
+ "io"
+ "net"
+)
+
+// Client is used for sending gemini requests and parsing gemini responses.
+//
+// It carries no state and is usable and reusable simultaneously by multiple goroutines.
+// The only reason you might create more than one Client is to support separate TLS-cert
+// driven identities.
+//
+// The zero value of Client is usable, it simply has no client TLS cert.
+type Client struct {
+ tlsConf *tls.Config
+}
+
+// Create a gemini Client with the given TLS configuration.
+func NewClient(tlsConf *tls.Config) Client {
+ return Client{tlsConf: tlsConf}
+}
+
+// RoundTrip sends a single gemini request to the correct server and returns its response.
+//
+// It also populates the TLSState and RemoteAddr fields on the request - the only field
+// it needs populated beforehand is the URL.
+func (client Client) RoundTrip(request *Request) (*Response, error) {
+ if request.Scheme != "gemini" && request.Scheme != "" {
+ return nil, errors.New("non-gemini protocols not supported")
+ }
+
+ host := request.Host
+ if _, port, _ := net.SplitHostPort(host); port == "" {
+ host += ":1965"
+ }
+
+ conn, err := tls.Dial("tcp", host, client.tlsConf)
+ if err != nil {
+ return nil, err
+ }
+ defer conn.Close()
+
+ request.RemoteAddr = conn.RemoteAddr()
+ st := conn.ConnectionState()
+ request.TLSState = &st
+
+ if _, err := conn.Write([]byte(request.URL.String() + "\r\n")); err != nil {
+ return nil, err
+ }
+
+ response, err := ParseResponse(conn)
+ if err != nil {
+ return nil, err
+ }
+
+ // read and store the request body in full or we may miss doing so before the
+ // connection gets closed.
+ bodybuf, err := io.ReadAll(response.Body)
+ if err != nil {
+ return nil, err
+ }
+ response.Body = bytes.NewBuffer(bodybuf)
+
+ return response, nil
+}