@cryptotaxi247 / kubo / commits / a3a843759

commands: Added marshalling to Response

Matt Bell committed Oct 10, 2014 at 13:33 UTC a3a843759b4ed6db41ac8b2c316bc27938b0e11d
1 file changed +33 -2
commands/response.go
+33 -2
@@ -1,5 +1,12 @@
1 package commands
2
3 +import (
4 + "fmt"
5 + "strings"
6 + "encoding/json"
7 + "encoding/xml"
8 +)
9 +
10 type ErrorType uint
11 const (
12 Normal ErrorType = iota // general errors
@@ -13,6 +20,19 @@ type Error struct {
20 code ErrorType
21 }
22
23 +type EncodingType string
24 +const (
25 + Json = "json"
26 + Xml = "xml"
27 + // TODO: support more encoding types
28 +)
29 +
30 +type Marshaller func(v interface{})([]byte, error)
31 +var marshallers = map[EncodingType]Marshaller{
32 + Json: json.Marshal,
33 + Xml: xml.Marshal,
34 +}
35 +
36 type Response struct {
37 req *Request
38 Error error
@@ -29,6 +49,17 @@ func (r *Response) FormatError() Error {
49 return Error{ r.Error.Error(), r.ErrorType }
50 }
51
32 -/*func (r *Response) Encode() ([]byte, error) {
52 +func (r *Response) Marshal() ([]byte, error) {
53 + enc := r.req.Option("enc")
54 + if enc == nil {
55 + return nil, fmt.Errorf("No encoding type was specified")
56 + }
57 + encType := EncodingType(strings.ToLower(enc.(string)))
58
34 -}*/
59 + marshaller, ok := marshallers[encType]
60 + if !ok {
61 + return nil, fmt.Errorf("No marshaller found for encoding type '%s'", enc)
62 + }
63 +
64 + return marshaller(r.Value)
65 +}