aboutsummaryrefslogtreecommitdiff
path: root/gemini.go
blob: 79a7c97494cc678ba9510cf5a948881f3925cf89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main

import (
	"crypto/tls"
	"fmt"
	"net/url"
	"os"
	"strconv"
	"strings"
)

const GeminiNetwork = "tcp"
const GeminiPort = 1965
const GeminiPrefix = "gemini://"

func FormatRequest(request string) []byte {
	if !strings.HasPrefix(request, GeminiPrefix) {
		request = GeminiPrefix + request
	}
	request = request + "\r\n"
	return []byte(request)
}

type GeminiConn struct {
	host   string
	config *tls.Config
}

func NewGeminiConn(request string, port int) (*GeminiConn, error) {
	if !strings.HasPrefix(request, "gemini://") {
		request = "gemini://" + request
	}

	u, err := url.Parse(request)
	if err != nil {
		return nil, err
	}

	conf := tls.Config{
		MinVersion:         tls.VersionTLS12,
		InsecureSkipVerify: true,
	}

	if strings.Contains(u.Host, ":") {
		return &GeminiConn{u.Host, &conf}, nil
	} else {
		return &GeminiConn{u.Host + ":" + strconv.Itoa(port), &conf}, nil
	}
}

func (c *GeminiConn) Get(request []byte, out *os.File) error {
	conn, err := tls.Dial(GeminiNetwork, c.host, c.config)
	if err != nil {
		return err
	}
	defer conn.Close()

	n, err := conn.Write(request)
	if err != nil {
		return err
	}

	buf := make([]byte, 1024)

	for {
		n, err = conn.Read(buf)
		if err != nil {
			return err
		}
		written, err := out.Write(buf[:n])
		if written != n {
			return fmt.Errorf("Got %d bytes, but only wrote %d bytes", n, written)
		}
		if err != nil {
			return err
		}

		if n == 0 {
			break
		}
	}
	return nil
}