~yotam/go-gemini

53586d2fb295e2e33daa37bfb673c0f879a532f3 — Yotam Nachum 5 years ago fe15cf0
Extract Fetch to a client struct

By extracting the Fetch function to a client struct we enable the
package user to pass configuration to the client without burdening the
function signature.
1 files changed, 15 insertions(+), 4 deletions(-)

M client.go
M client.go => client.go +15 -4
@@ 22,9 22,15 @@ type header struct {
	meta   string
}

type Client struct {
	InsecureSkipVerify bool
}

var DefaultClient = &Client{}

// Fetch a resource from a Gemini server with the given URL
func Fetch(url string) (res Response, err error) {
	conn, err := connectByURL(url)
func (c Client) Fetch(url string) (res Response, err error) {
	conn, err := c.connect(url)
	if err != nil {
		return Response{}, fmt.Errorf("failed to connect to the server: %v", err)
	}


@@ 38,19 44,24 @@ func Fetch(url string) (res Response, err error) {
	return getResponse(conn)
}

func connectByURL(rawURL string) (io.ReadWriteCloser, error) {
func (c Client) connect(rawURL string) (io.ReadWriteCloser, error) {
	parsedURL, err := url.Parse(rawURL)
	if err != nil {
		return nil, fmt.Errorf("failed to parse given URL: %v", err)
	}

	conf := &tls.Config{
		InsecureSkipVerify: true,
		InsecureSkipVerify: c.InsecureSkipVerify,
	}

	return tls.Dial("tcp", parsedURL.Host, conf)
}

// Fetch a resource from a Gemini server with the default client
func Fetch(url string) (res Response, err error) {
	return DefaultClient.Fetch(url)
}

func sendRequest(conn io.Writer, requestURL string) error {
	_, err := fmt.Fprintf(conn, "%s\r\n", requestURL)
	if err != nil {