ping.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2019 The gRPC Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package http2interop
  15. import (
  16. "fmt"
  17. "io"
  18. )
  19. type PingFrame struct {
  20. Header FrameHeader
  21. Data []byte
  22. }
  23. const (
  24. PING_ACK = 0x01
  25. )
  26. func (f *PingFrame) GetHeader() *FrameHeader {
  27. return &f.Header
  28. }
  29. func (f *PingFrame) ParsePayload(r io.Reader) error {
  30. raw := make([]byte, f.Header.Length)
  31. if _, err := io.ReadFull(r, raw); err != nil {
  32. return err
  33. }
  34. return f.UnmarshalPayload(raw)
  35. }
  36. func (f *PingFrame) UnmarshalPayload(raw []byte) error {
  37. if f.Header.Length != len(raw) {
  38. return fmt.Errorf("Invalid Payload length %d != %d", f.Header.Length, len(raw))
  39. }
  40. if f.Header.Length != 8 {
  41. return fmt.Errorf("Invalid Payload length %d", f.Header.Length)
  42. }
  43. f.Data = []byte(string(raw))
  44. return nil
  45. }
  46. func (f *PingFrame) MarshalPayload() ([]byte, error) {
  47. if len(f.Data) != 8 {
  48. return nil, fmt.Errorf("Invalid Payload length %d", len(f.Data))
  49. }
  50. return []byte(string(f.Data)), nil
  51. }
  52. func (f *PingFrame) MarshalBinary() ([]byte, error) {
  53. payload, err := f.MarshalPayload()
  54. if err != nil {
  55. return nil, err
  56. }
  57. f.Header.Length = len(payload)
  58. f.Header.Type = PingFrameType
  59. header, err := f.Header.MarshalBinary()
  60. if err != nil {
  61. return nil, err
  62. }
  63. header = append(header, payload...)
  64. return header, nil
  65. }