aboutsummaryrefslogtreecommitdiff
path: root/gemini.go
blob: 1cdef8b12952d57d3e79b4361347a962fb3af78b (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
84
85
86
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(host string, port int) *GeminiConn {
	conf := tls.Config{
		MinVersion:         tls.VersionTLS12,
		InsecureSkipVerify: true,
	}

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

func NewGeminiConnFromRequest(request string, port int) (*GeminiConn, error) {
	if !strings.HasPrefix(request, GeminiPrefix) {
		request = GeminiPrefix + request
	}

	u, err := url.Parse(request)
	if err != nil {
		return nil, err
	}
	return NewGeminiConn(u.Host, port), 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
}