response.go 3.54 KB
Newer Older
Matt Bell's avatar
Matt Bell committed
1 2
package commands

3
import (
4
	"bytes"
Matt Bell's avatar
Matt Bell committed
5 6 7
	"encoding/json"
	"encoding/xml"
	"fmt"
8
	"io"
Matt Bell's avatar
Matt Bell committed
9
	"strings"
10 11
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
// ErrorType signfies a category of errors
Matt Bell's avatar
Matt Bell committed
13
type ErrorType uint
Matt Bell's avatar
Matt Bell committed
14

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
// ErrorTypes convey what category of error ocurred
Matt Bell's avatar
Matt Bell committed
16
const (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18
	ErrNormal ErrorType = iota // general errors
	ErrClient                  // error was caused by the client, (e.g. invalid CLI usage)
Matt Bell's avatar
Matt Bell committed
19
	// TODO: add more types of errors for better error-specific handling
Matt Bell's avatar
Matt Bell committed
20 21
)

22 23
// Error is a struct for marshalling errors
type Error struct {
Matt Bell's avatar
Matt Bell committed
24 25
	Message string
	Code    ErrorType
26 27
}

28
func (e Error) Error() string {
29
	return e.Message
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30 31 32
}

// EncodingType defines a supported encoding
33
type EncodingType string
Matt Bell's avatar
Matt Bell committed
34

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35
// Supported EncodingType constants.
36
const (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37 38
	JSON = "json"
	XML  = "xml"
39
	Text = "text"
Matt Bell's avatar
Matt Bell committed
40
	// TODO: support more encoding types
41 42 43
)

var marshallers = map[EncodingType]Marshaller{
44 45
	JSON: func(res Response) ([]byte, error) {
		if res.Error() != nil {
46
			return json.MarshalIndent(res.Error(), "", "  ")
47
		}
48
		return json.MarshalIndent(res.Output(), "", "  ")
49 50 51 52 53
	},
	XML: func(res Response) ([]byte, error) {
		if res.Error() != nil {
			return xml.Marshal(res.Error())
		}
54
		return xml.Marshal(res.Output())
55
	},
56 57
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58 59
// Response is the result of a command request. Handlers write to the response,
// setting Error or Value. Response is returned to the client.
60 61 62 63 64
type Response interface {
	Request() Request

	// Set/Return the response Error
	SetError(err error, code ErrorType)
65
	Error() *Error
66 67

	// Sets/Returns the response value
68 69
	SetOutput(interface{})
	Output() interface{}
70 71 72 73

	// Marshal marshals out the response into a buffer. It uses the EncodingType
	// on the Request to chose a Marshaller (Codec).
	Marshal() ([]byte, error)
74 75 76

	// Gets a io.Reader that reads the marshalled output
	Reader() (io.Reader, error)
77 78 79 80 81 82
}

type response struct {
	req   Request
	err   *Error
	value interface{}
83
	out   io.Reader
84 85 86 87 88 89
}

func (r *response) Request() Request {
	return r.req
}

90
func (r *response) Output() interface{} {
91 92 93
	return r.value
}

94
func (r *response) SetOutput(v interface{}) {
95 96 97
	r.value = v
}

98
func (r *response) Error() *Error {
99
	return r.err
Matt Bell's avatar
Matt Bell committed
100 101
}

102 103
func (r *response) SetError(err error, code ErrorType) {
	r.err = &Error{Message: err.Error(), Code: code}
104 105
}

106 107
func (r *response) Marshal() ([]byte, error) {
	if r.err == nil && r.value == nil {
108
		return []byte{}, nil
Matt Bell's avatar
Matt Bell committed
109
	}
110

111
	if !r.req.Option(EncShort).Found() {
Matt Bell's avatar
Matt Bell committed
112 113
		return nil, fmt.Errorf("No encoding type was specified")
	}
114 115 116 117 118
	enc, err := r.req.Option(EncShort).String()
	if err != nil {
		return nil, err
	}
	encType := EncodingType(strings.ToLower(enc))
Matt Bell's avatar
Matt Bell committed
119

120 121 122 123
	var marshaller Marshaller
	if r.req.Command() != nil && r.req.Command().Marshallers != nil {
		marshaller = r.req.Command().Marshallers[encType]
	}
124
	if marshaller == nil {
125
		var ok bool
126 127 128 129
		marshaller, ok = marshallers[encType]
		if !ok {
			return nil, fmt.Errorf("No marshaller found for encoding type '%s'", enc)
		}
Matt Bell's avatar
Matt Bell committed
130
	}
131

132
	return marshaller(r)
133 134
}

135 136 137 138
// Reader returns an `io.Reader` representing marshalled output of this Response
// Note that multiple calls to this will return a reference to the same io.Reader
func (r *response) Reader() (io.Reader, error) {
	// if command set value to a io.Reader, use that as our reader
139 140 141 142 143 144
	if r.out == nil {
		if out, ok := r.value.(io.Reader); ok {
			r.out = out
		}
	}

145 146 147 148 149 150
	if r.out == nil {
		// no reader set, so marshal the error or value
		marshalled, err := r.Marshal()
		if err != nil {
			return nil, err
		}
151

152 153
		// create a Reader from the marshalled data
		r.out = bytes.NewReader(marshalled)
154 155
	}

156
	return r.out, nil
157 158
}

159
// NewResponse returns a response to match given Request
160 161
func NewResponse(req Request) Response {
	return &response{req: req}
162
}