Make Request implement io.WriterTo

This commit is contained in:
Adnan Maolood 2021-02-28 22:16:38 -05:00
parent ae7d58549d
commit 768ec6c17b
3 changed files with 15 additions and 10 deletions

View File

@ -153,7 +153,7 @@ func (c *Client) do(ctx context.Context, conn net.Conn, req *Request) (*Response
} }
// Write the request // Write the request
if err := req.Write(w); err != nil { if _, err := req.WriteTo(w); err != nil {
return nil, err return nil, err
} }

View File

@ -77,21 +77,26 @@ func ReadRequest(r io.Reader) (*Request, error) {
return &Request{URL: u}, nil return &Request{URL: u}, nil
} }
// Write writes a Gemini request in wire format. // WriteTo writes r to w in the Gemini request format.
// This method consults the request URL only. // This method consults the request URL only.
func (r *Request) Write(w io.Writer) error { func (r *Request) WriteTo(w io.Writer) (int, error) {
bw := bufio.NewWriterSize(w, 1026) bw := bufio.NewWriterSize(w, 1026)
url := r.URL.String() url := r.URL.String()
if len(url) > 1024 { if len(url) > 1024 {
return ErrInvalidRequest return 0, ErrInvalidRequest
} }
if _, err := bw.WriteString(url); err != nil { var wrote int
return err n, err := bw.WriteString(url)
wrote += n
if err != nil {
return wrote, err
} }
if _, err := bw.Write(crlf); err != nil { n, err = bw.Write(crlf)
return err wrote += n
if err != nil {
return wrote, err
} }
return bw.Flush() return wrote, bw.Flush()
} }
// Conn returns the network connection on which the request was received. // Conn returns the network connection on which the request was received.

View File

@ -119,7 +119,7 @@ func TestWriteRequest(t *testing.T) {
t.Logf("%s", test.Req.URL) t.Logf("%s", test.Req.URL)
var b strings.Builder var b strings.Builder
bw := bufio.NewWriter(&b) bw := bufio.NewWriter(&b)
err := test.Req.Write(bw) _, err := test.Req.WriteTo(bw)
if err != test.Err { if err != test.Err {
t.Errorf("expected err = %v, got %v", test.Err, err) t.Errorf("expected err = %v, got %v", test.Err, err)
} }