summaryrefslogtreecommitdiffstats
path: root/client.go
blob: b208637cb45420cad06ca537038aebb26f39f6ac (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
package cnp

import (
	"net"
	"strconv"
	"strings"
)

// TODO: make more modular and extensible like net/http

// Send sends a CNP request to a server and returns the response.
//
// The TCP connection is made using net.Dial.
func Send(r *Request) (*Response, error) {
	host := r.Host()
	if strings.LastIndexByte(host, ':') <= strings.LastIndexByte(host, ']') { // missing/default port
		host = net.JoinHostPort(host, strconv.Itoa(DefaultPort))
	}
	conn, err := net.Dial("tcp", host)
	if err != nil {
		return nil, err
	}
	if err = r.Write(conn); err != nil {
		return nil, err
	}
	if err = r.Close(); err != nil {
		return nil, err
	}
	return ParseResponse(conn)
}

// Get sends a body-less request to a given URL.
func Get(url string) (*Response, error) {
	req, err := NewRequestURL(url, nil)
	if err != nil {
		return nil, err
	}
	return Send(req)
}