join.go 913 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Copyright 2019 The Gorilla WebSocket 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 websocket
  5. import (
  6. "io"
  7. "strings"
  8. )
  9. // JoinMessages concatenates received messages to create a single io.Reader.
  10. // The string term is appended to each message. The returned reader does not
  11. // support concurrent calls to the Read method.
  12. func JoinMessages(c *Conn, term string) io.Reader {
  13. return &joinReader{c: c, term: term}
  14. }
  15. type joinReader struct {
  16. c *Conn
  17. term string
  18. r io.Reader
  19. }
  20. func (r *joinReader) Read(p []byte) (int, error) {
  21. if r.r == nil {
  22. var err error
  23. _, r.r, err = r.c.NextReader()
  24. if err != nil {
  25. return 0, err
  26. }
  27. if r.term != "" {
  28. r.r = io.MultiReader(r.r, strings.NewReader(r.term))
  29. }
  30. }
  31. n, err := r.r.Read(p)
  32. if err == io.EOF {
  33. err = nil
  34. r.r = nil
  35. }
  36. return n, err
  37. }