1
// Copyright (c) 2020 Uber Technologies, Inc.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a copy
4
// of this software and associated documentation files (the "Software"), to deal
5
// in the Software without restriction, including without limitation the rights
6
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
// copies of the Software, and to permit persons to whom the Software is
8
// furnished to do so, subject to the following conditions:
9
//
10
// The above copyright notice and this permission notice shall be included in
11
// all copies or substantial portions of the Software.
12
//
13
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
// THE SOFTWARE.
20

21
package envelope
22

23
import (
24
	"fmt"
25
	"io"
26

27
	"go.uber.org/thriftrw/internal/envelope/exception"
28
	"go.uber.org/thriftrw/protocol"
29
	"go.uber.org/thriftrw/wire"
30
)
31

32
// Enveloper is the interface implemented by a type that can be written with
33
// an envelope.
34
type Enveloper interface {
35
	MethodName() string
36
	EnvelopeType() wire.EnvelopeType
37
	ToWire() (wire.Value, error)
38
}
39

40
// Write writes an Envelope to the given writer.
41 2
func Write(p protocol.Protocol, w io.Writer, seqID int32, e Enveloper) error {
42 2
	body, err := e.ToWire()
43 2
	if err != nil {
44 2
		return err
45
	}
46 2
	return p.EncodeEnveloped(wire.Envelope{
47 2
		SeqID: seqID,
48 2
		Name:  e.MethodName(),
49 2
		Type:  e.EnvelopeType(),
50 2
		Value: body,
51 2
	}, w)
52
}
53

54
// ReadReply reads enveloped responses from the given reader.
55 2
func ReadReply(p protocol.Protocol, r io.ReaderAt) (_ wire.Value, seqID int32, _ error) {
56 2
	envelope, err := p.DecodeEnveloped(r)
57 2
	if err != nil {
58 2
		return wire.Value{}, 0, err
59
	}
60

61 2
	switch {
62 2
	case envelope.Type == wire.Reply:
63 2
		return envelope.Value, envelope.SeqID, nil
64 2
	case envelope.Type != wire.Exception:
65 2
		return envelope.Value, envelope.SeqID, fmt.Errorf("unknown envelope type for reply, got %v", envelope.Type)
66
	}
67

68
	// Decode the exception payload.
69 2
	ex := &exception.TApplicationException{}
70 2
	if err := ex.FromWire(envelope.Value); err != nil {
71 0
		return envelope.Value, envelope.SeqID, fmt.Errorf("failed to decode exception: %v", err)
72
	}
73

74 2
	return envelope.Value, envelope.SeqID, ex
75
}

Read our documentation on viewing source code .

Loading