// 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 }