go-gemini/request.go

83 lines
2.1 KiB
Go
Raw Normal View History

2020-10-24 13:15:32 -06:00
package gemini
2020-10-21 15:07:28 -06:00
import (
"bufio"
2020-11-25 22:42:25 -07:00
"context"
2020-10-21 15:07:28 -06:00
"crypto/tls"
"net"
"net/url"
)
// Request represents a Gemini request.
type Request struct {
// URL specifies the URL being requested.
URL *url.URL
// For client requests, Host specifies the host on which the URL is sought.
// Host must contain a port.
// This field is ignored by the server.
Host string
// Certificate specifies the TLS certificate to use for the request.
// Request certificates take precedence over client certificates.
//
// On the server side, if the client provided a certificate then
// Certificate.Leaf is guaranteed to be non-nil.
2020-10-21 15:07:28 -06:00
Certificate *tls.Certificate
// RemoteAddr allows servers and other software to record the network
// address that sent the request.
// This field is ignored by the client.
RemoteAddr net.Addr
// TLS allows servers and other software to record information about the TLS
// connection on which the request was received.
// This field is ignored by the client.
TLS tls.ConnectionState
2020-11-25 22:42:25 -07:00
// Context specifies the context to use for client requests.
2020-12-17 15:16:55 -07:00
// If Context is nil, the background context will be used.
2020-11-25 22:42:25 -07:00
Context context.Context
2020-10-21 15:07:28 -06:00
}
2020-10-27 11:27:52 -06:00
// NewRequest returns a new request. The host is inferred from the URL.
2020-10-21 15:07:28 -06:00
func NewRequest(rawurl string) (*Request, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
2020-11-04 21:46:05 -07:00
return NewRequestFromURL(u), nil
2020-10-27 11:27:52 -06:00
}
2020-10-21 15:07:28 -06:00
2020-10-27 11:27:52 -06:00
// NewRequestFromURL returns a new request for the given URL.
// The host is inferred from the URL.
2020-11-27 20:26:22 -07:00
//
// Callers should be careful that the URL query is properly escaped.
// See the documentation for QueryEscape for more information.
2020-11-04 21:46:05 -07:00
func NewRequestFromURL(url *url.URL) *Request {
2020-10-27 11:27:52 -06:00
host := url.Host
if url.Port() == "" {
2020-10-21 15:07:28 -06:00
host += ":1965"
}
return &Request{
2020-12-17 15:16:55 -07:00
URL: url,
Host: host,
2020-11-04 21:46:05 -07:00
}
2020-10-21 15:07:28 -06:00
}
// write writes the Gemini request to the provided buffered writer.
func (r *Request) write(w *bufio.Writer) error {
url := r.URL.String()
// User is invalid
if r.URL.User != nil || len(url) > 1024 {
return ErrInvalidURL
}
if _, err := w.WriteString(url); err != nil {
return err
}
if _, err := w.Write(crlf); err != nil {
return err
}
return nil
}