Encoder.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (c) 2014 by Farsight Security, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package framestream
  17. import (
  18. "io"
  19. "time"
  20. )
  21. // EncoderOptions specifies configuration for an Encoder
  22. type EncoderOptions struct {
  23. // The ContentType of the data sent by the Encoder. May be left unset
  24. // for no content negotiation. If the Reader requests a different
  25. // content type, NewEncoder() will return ErrContentTypeMismatch.
  26. ContentType []byte
  27. // If Bidirectional is true, the underlying io.Writer must be an
  28. // io.ReadWriter, and the Encoder will engage in a bidirectional
  29. // handshake with its peer to establish content type and communicate
  30. // shutdown.
  31. Bidirectional bool
  32. // Timeout gives the timeout for writing both control and data frames,
  33. // and for reading responses to control frames sent. It is only
  34. // effective for underlying Writers satisfying net.Conn.
  35. Timeout time.Duration
  36. }
  37. // An Encoder sends data frames over a FrameStream Writer.
  38. //
  39. // Encoder is provided for compatibility, use Writer instead.
  40. type Encoder struct {
  41. *Writer
  42. }
  43. // NewEncoder creates an Encoder writing to the given io.Writer with the given
  44. // EncoderOptions.
  45. func NewEncoder(w io.Writer, opt *EncoderOptions) (enc *Encoder, err error) {
  46. if opt == nil {
  47. opt = &EncoderOptions{}
  48. }
  49. wopt := &WriterOptions{
  50. Bidirectional: opt.Bidirectional,
  51. Timeout: opt.Timeout,
  52. }
  53. if opt.ContentType != nil {
  54. wopt.ContentTypes = append(wopt.ContentTypes, opt.ContentType)
  55. }
  56. writer, err := NewWriter(w, wopt)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return &Encoder{Writer: writer}, nil
  61. }
  62. func (e *Encoder) Write(frame []byte) (int, error) {
  63. return e.WriteFrame(frame)
  64. }