summaryrefslogtreecommitdiff
path: root/nex/client.go
blob: 5f537464b524a57df9f6077c98119e130f582fe4 (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
package nex

import (
	"bytes"
	"errors"
	"io"
	"net"
	neturl "net/url"

	"tildegit.org/tjp/sliderule/internal/types"
)

// Client is used for sending nex requests and reading responses.
//
// It carries no state and is reusable simultaneously by multiple goroutines.
//
// The zero value is immediately usable.
type Client struct{}

// RoundTrip sends a single nex request and returns its response.
func (c Client) RoundTrip(request *types.Request) (*types.Response, error) {
	if request.Scheme != "nex" && request.Scheme != "" {
		return nil, errors.New("non-nex protocols not supported")
	}

	host := request.Host
	if _, port, _ := net.SplitHostPort(host); port == "" {
		host = net.JoinHostPort(host, "1900")
	}

	conn, err := net.Dial("tcp", host)
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	request.RemoteAddr = conn.RemoteAddr()
	request.TLSState = nil

	if _, err := conn.Write([]byte(request.Path + "\n")); err != nil {
		return nil, err
	}

	response, err := io.ReadAll(conn)
	if err != nil {
		return nil, err
	}

	return &types.Response{Body: bytes.NewBuffer(response)}, nil
}

// Fetch builds and sends a nex request, and returns the response.
func (c Client) Fetch(url string) (*types.Response, error) {
	u, err := neturl.Parse(url)
	if err != nil {
		return nil, err
	}
	return c.RoundTrip(&types.Request{URL: u})
}

func (c Client) IsRedirect(response *types.Response) bool { return false }