Skip to content

Commit

Permalink
fixup! fixup! fixup! fixup! fixup! Allow API methods be able to respo…
Browse files Browse the repository at this point in the history
…nd with a generic reponse
  • Loading branch information
fperot74 committed Jun 5, 2019
1 parent b7ec231 commit 73ec38f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 16 deletions.
16 changes: 8 additions & 8 deletions http/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ type MimeContent struct {

// GenericResponse for HTTP requests
type GenericResponse struct {
StatusCode int
Headers map[string]string
MimeContent *MimeContent
ExportToJSON interface{}
StatusCode int
Headers map[string]string
MimeContent *MimeContent
JSONableResponse interface{}
}

// WriteResponse writes a response for a mime content type
Expand All @@ -53,15 +53,15 @@ func (r *GenericResponse) WriteResponse(w http.ResponseWriter) {
// Body
if r.MimeContent != nil {
w.Write(r.MimeContent.Content)
} else if r.ExportToJSON != nil {
writeJSON(r.ExportToJSON, w)
} else if r.JSONableResponse != nil {
writeJSON(r.JSONableResponse, w)
}
}

func writeJSON(exportToJSON interface{}, w http.ResponseWriter) {
func writeJSON(jsonableResponse interface{}, w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")

var json, err = json.MarshalIndent(exportToJSON, "", " ")
var json, err = json.MarshalIndent(jsonableResponse, "", " ")

if err == nil {
w.Write(json)
Expand Down
16 changes: 8 additions & 8 deletions http/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ func TestHttpGenericResponse(t *testing.T) {
// Test with JSON content
r.Handle("/path/to/mime", makeHandler(func(_ context.Context, _ interface{}) (response interface{}, err error) {
return GenericResponse{
StatusCode: http.StatusNotFound,
Headers: map[string]string{"Location": "here"},
MimeContent: nil,
ExportToJSON: make([]int, 0),
StatusCode: http.StatusNotFound,
Headers: map[string]string{"Location": "here"},
MimeContent: nil,
JSONableResponse: make([]int, 0),
}, nil
}))
// Test with MimeContent
Expand All @@ -55,10 +55,10 @@ func TestHttpGenericResponse(t *testing.T) {
Filename: "filename.jpg",
}
return GenericResponse{
StatusCode: http.StatusCreated,
Headers: nil,
MimeContent: &mime,
ExportToJSON: nil,
StatusCode: http.StatusCreated,
Headers: nil,
MimeContent: &mime,
JSONableResponse: nil,
}, nil
}))

Expand Down

0 comments on commit 73ec38f

Please sign in to comment.