summaryrefslogtreecommitdiff
path: root/client/client.go
blob: b68b2be3c3a72d3b40029cc3e29826fcd247b58a (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
// Package client makes requests to a Caesar Cipher Server in order to encode
// and decode messages.
package client

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"sync"
	"time"
)

// A CaesarClient handles communication with a server
type CaesarClient struct {
	// Endpoint is the URL to which HTTP requests should be made
	Endpoint string

	c    *http.Client
	once sync.Once
}

// EncodeMessage asks the Caesar server to encode the supplied message and
// returns the result along with an error in case the request fails.
func (c *CaesarClient) EncodeMessage(r io.Reader) (io.Reader, error) {
	c.once.Do(func() {
		c.c = &http.Client{Timeout: 10 * time.Second}
	})
	req, err := http.NewRequest("POST", c.Endpoint, r)
	if err != nil {
		return nil, err
	}
	req.Header.Set("user-agent", "caesar-client/1.0")
	resp, err := c.c.Do(req)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("http status %s", resp.Status)
	}
	var body bytes.Buffer
	defer resp.Body.Close()
	if _, err := io.Copy(&body, resp.Body); err != nil {
		return nil, err
	}
	return &body, nil
}