| 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 |
|
| 15 |
package http2interop |
| 16 |
|
| 17 |
import ( |
| 18 |
"fmt" |
| 19 |
"io" |
| 20 |
) |
| 21 |
|
| 22 |
type PingFrame struct { |
| 23 |
Header FrameHeader |
| 24 |
Data []byte |
| 25 |
} |
| 26 |
|
| 27 |
const ( |
| 28 |
PING_ACK = 0x01 |
| 29 |
) |
| 30 |
|
| 31 |
func (f *PingFrame) GetHeader() *FrameHeader { |
| 32 |
return &f.Header |
| 33 |
} |
| 34 |
|
| 35 |
func (f *PingFrame) ParsePayload(r io.Reader) error { |
| 36 |
raw := make([]byte, f.Header.Length) |
| 37 |
if _, err := io.ReadFull(r, raw); err != nil { |
| 38 |
return err |
| 39 |
} |
| 40 |
return f.UnmarshalPayload(raw) |
| 41 |
} |
| 42 |
|
| 43 |
func (f *PingFrame) UnmarshalPayload(raw []byte) error { |
| 44 |
if f.Header.Length != len(raw) { |
| 45 |
return fmt.Errorf("Invalid Payload length %d != %d", f.Header.Length, len(raw)) |
| 46 |
} |
| 47 |
if f.Header.Length != 8 { |
| 48 |
return fmt.Errorf("Invalid Payload length %d", f.Header.Length) |
| 49 |
} |
| 50 |
|
| 51 |
f.Data = []byte(string(raw)) |
| 52 |
|
| 53 |
return nil |
| 54 |
} |
| 55 |
|
| 56 |
func (f *PingFrame) MarshalPayload() ([]byte, error) { |
| 57 |
if len(f.Data) != 8 { |
| 58 |
return nil, fmt.Errorf("Invalid Payload length %d", len(f.Data)) |
| 59 |
} |
| 60 |
return []byte(string(f.Data)), nil |
| 61 |
} |
| 62 |
|
| 63 |
func (f *PingFrame) MarshalBinary() ([]byte, error) { |
| 64 |
payload, err := f.MarshalPayload() |
| 65 |
if err != nil { |
| 66 |
return nil, err |
| 67 |
} |
| 68 |
|
| 69 |
f.Header.Length = len(payload) |
| 70 |
f.Header.Type = PingFrameType |
| 71 |
header, err := f.Header.MarshalBinary() |
| 72 |
if err != nil { |
| 73 |
return nil, err |
| 74 |
} |
| 75 |
|
| 76 |
header = append(header, payload...) |
| 77 |
|
| 78 |
return header, nil |
| 79 |
} |