summaryrefslogtreecommitdiff
path: root/spartan/client.go
blob: 154b18a612d24eebc6c07db88c7b4459ae7dc449 (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
package spartan

import (
	"bytes"
	"errors"
	"io"
	"net"
	"strconv"

	"tildegit.org/tjp/gus"
)

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

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

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

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

	request.RemoteAddr = conn.RemoteAddr()

	var bodyBytes []byte = nil
	if body != nil {
		bodyBytes, err = io.ReadAll(body)
		if err != nil {
			return nil, err
		}
	}

	requestLine := host + " " + request.EscapedPath() + " " + strconv.Itoa(len(bodyBytes)) + "\r\n"

	if _, err := conn.Write([]byte(requestLine)); err != nil {
		return nil, err
	}
	if _, err := conn.Write(bodyBytes); err != nil {
		return nil, err
	}

	response, err := ParseResponse(conn)
	if err != nil {
		return nil, err
	}

	bodybuf, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	response.Body = bytes.NewBuffer(bodybuf)

	return response, nil
}