From bd51133fbda340542ec29ec1035b028ea112e028 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Wed, 19 May 2021 13:41:13 +0700 Subject: xmlrpc: add method to marshal Response --- lib/xmlrpc/response.go | 26 +++++++++++++++++++++++ lib/xmlrpc/response_test.go | 52 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/lib/xmlrpc/response.go b/lib/xmlrpc/response.go index 1e0343de..53d35a1f 100644 --- a/lib/xmlrpc/response.go +++ b/lib/xmlrpc/response.go @@ -17,6 +17,32 @@ type Response struct { IsFault bool } +// +// MarshalText encode the Response instance into XML text. +// +func (resp *Response) MarshalText() (out []byte, err error) { + var buf bytes.Buffer + + buf.WriteString(xml.Header) + buf.WriteString("") + + if !resp.IsFault { + fmt.Fprintf(&buf, "%s", + resp.Param) + } else { + buf.WriteString("") + fmt.Fprintf(&buf, "faultCode%d", + resp.FaultCode) + fmt.Fprintf(&buf, "faultString%s", + resp.FaultMessage) + buf.WriteString("") + } + + buf.WriteString("") + + return buf.Bytes(), nil +} + func (resp *Response) UnmarshalText(text []byte) (err error) { var ( logp = "xmlrpc: Response" diff --git a/lib/xmlrpc/response_test.go b/lib/xmlrpc/response_test.go index 6a6f9e0f..23c61312 100644 --- a/lib/xmlrpc/response_test.go +++ b/lib/xmlrpc/response_test.go @@ -5,12 +5,60 @@ package xmlrpc import ( + "encoding/xml" "testing" "github.com/shuLhan/share/lib/test" ) -func TestResponse(t *testing.T) { +func TestResponse_MarshalText(t *testing.T) { + cases := []struct { + desc string + resp *Response + exp string + }{{ + desc: "With param", + resp: &Response{ + Param: &Value{ + Kind: Boolean, + In: true, + }, + }, + exp: xml.Header + `true`, + }, { + desc: "With fault", + resp: &Response{ + FaultCode: 404, + FaultMessage: "Not found", + IsFault: true, + }, + exp: xml.Header + `` + + `` + + `` + + `faultCode` + + `404` + + `` + + `` + + `faultString` + + `Not found` + + `` + + `` + + ``, + }} + + for _, c := range cases { + t.Logf(c.desc) + + got, err := c.resp.MarshalText() + if err != nil { + t.Fatal(err) + } + + test.Assert(t, "MarshalText", c.exp, string(got)) + } +} + +func TestResponse_UnmarshalText(t *testing.T) { cases := []struct { desc string text string @@ -91,6 +139,8 @@ func TestResponse(t *testing.T) { }} for _, c := range cases { + t.Logf(c.desc) + var got Response err := got.UnmarshalText([]byte(c.text)) -- cgit v1.3