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

import (
	"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, writes
// the encoded message to the supplied writer, and returns an error in case the
// request fails.
func (c *CaesarClient) EncodeMessage(w io.Writer, r 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 err
	}
	req.Header.Set("user-agent", "caesar-client/1.0")
	resp, err := c.c.Do(req)
	if err != nil {
		return err
	}
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("http status %s", resp.Status)
	}
	defer resp.Body.Close()
	if _, err := io.Copy(w, resp.Body); err != nil {
		return err
	}
	return nil
}