// 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 // Token is an authorization token to supply to the server Token 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("authorization", "token "+c.Token) 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 }