Skip to content

Commit

Permalink
Merge pull request #94 from tsawler/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
tsawler committed Apr 7, 2023
2 parents 3f9c55d + b352166 commit 55e304a
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ The included tools are:
- Produce a JSON encoded error response
- Write XML
- Read XML
- Produce an XML encoded error response
- Upload a file to a specified directory
- Download a static file
- Get a random string of length n
Expand Down
17 changes: 17 additions & 0 deletions tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,20 @@ func (t *Tools) ReadXML(w http.ResponseWriter, r *http.Request, data interface{}

return nil
}

// ErrorXML takes an error, and optionally a response status code, and generates and sends
// an XML error response.
func (t *Tools) ErrorXML(w http.ResponseWriter, err error, status ...int) error {
statusCode := http.StatusBadRequest

// if a custom response code is specified, use that instead of bad request
if len(status) > 0 {
statusCode = status[0]
}

var payload XMLResponse
payload.Error = true
payload.Message = err.Error()

return t.WriteXML(w, statusCode, payload)
}
26 changes: 26 additions & 0 deletions tools_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package toolbox
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"image"
Expand Down Expand Up @@ -539,3 +540,28 @@ func TestTools_ReadXML(t *testing.T) {
}
}
}

func TestTools_ErrorXML(t *testing.T) {
var testTools Tools

rr := httptest.NewRecorder()
err := testTools.ErrorXML(rr, errors.New("some error"), http.StatusServiceUnavailable)
if err != nil {
t.Error(err)
}

var requestPayload XMLResponse
decoder := xml.NewDecoder(rr.Body)
err = decoder.Decode(&requestPayload)
if err != nil {
t.Error("received error when decoding ErrorXML payload:", err)
}

if !requestPayload.Error {
t.Error("error set to false in response from ErrorXML, and should be set to true")
}

if rr.Code != http.StatusServiceUnavailable {
t.Errorf("wrong status code returned; expected 503, but got %d", rr.Code)
}
}

0 comments on commit 55e304a

Please sign in to comment.