/http/chunked.go

http://github.com/petar/GoHTTP · Go · 77 lines · 42 code · 11 blank · 24 comment · 9 complexity · 9f6b87e55f6b29d966d1bcdc1d44ab4a MD5 · raw file

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package http
  5. import (
  6. "bufio"
  7. "io"
  8. "log"
  9. "os"
  10. "strconv"
  11. )
  12. // NewChunkedWriter returns a new writer that translates writes into HTTP
  13. // "chunked" format before writing them to w. Closing the returned writer
  14. // sends the final 0-length chunk that marks the end of the stream.
  15. //
  16. // NewChunkedWriter is not needed by normal applications. The http
  17. // package adds chunking automatically if handlers don't set a
  18. // Content-Length header. Using NewChunkedWriter inside a handler
  19. // would result in double chunking or chunking with a Content-Length
  20. // length, both of which are wrong.
  21. func NewChunkedWriter(w io.Writer) io.WriteCloser {
  22. if _, bad := w.(*response); bad {
  23. log.Printf("warning: using NewChunkedWriter in an http.Handler; expect corrupt output")
  24. }
  25. return &chunkedWriter{w}
  26. }
  27. // Writing to ChunkedWriter translates to writing in HTTP chunked Transfer
  28. // Encoding wire format to the underlying Wire writer.
  29. type chunkedWriter struct {
  30. Wire io.Writer
  31. }
  32. // Write the contents of data as one chunk to Wire.
  33. // NOTE: Note that the corresponding chunk-writing procedure in Conn.Write has
  34. // a bug since it does not check for success of io.WriteString
  35. func (cw *chunkedWriter) Write(data []byte) (n int, err os.Error) {
  36. // Don't send 0-length data. It looks like EOF for chunked encoding.
  37. if len(data) == 0 {
  38. return 0, nil
  39. }
  40. head := strconv.Itob(len(data), 16) + "\r\n"
  41. if _, err = io.WriteString(cw.Wire, head); err != nil {
  42. return 0, err
  43. }
  44. if n, err = cw.Wire.Write(data); err != nil {
  45. return
  46. }
  47. if n != len(data) {
  48. err = io.ErrShortWrite
  49. return
  50. }
  51. _, err = io.WriteString(cw.Wire, "\r\n")
  52. return
  53. }
  54. func (cw *chunkedWriter) Close() os.Error {
  55. _, err := io.WriteString(cw.Wire, "0\r\n")
  56. return err
  57. }
  58. // NewChunkedReader returns a new reader that translates the data read from r
  59. // out of HTTP "chunked" format before returning it.
  60. // The reader returns os.EOF when the final 0-length chunk is read.
  61. //
  62. // NewChunkedReader is not needed by normal applications. The http package
  63. // automatically decodes chunking when reading response bodies.
  64. func NewChunkedReader(r *bufio.Reader) io.Reader {
  65. return &chunkedReader{r: r}
  66. }