Skip to content

Commit

Permalink
feat: post setting response status code
Browse files Browse the repository at this point in the history
  • Loading branch information
vinyguedess committed Mar 10, 2022
1 parent 0cf442a commit 8cbe521
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
1 change: 1 addition & 0 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ func Handler(handler EasyHandler) MuxHandler {
response := NewResponse(responseWriter)

receivedResponse := handler(request, response)
responseWriter.WriteHeader(receivedResponse.GetStatus())
for key, value := range receivedResponse.GetHeaders() {
responseWriter.Header().Set(key, value)
}
Expand Down
13 changes: 11 additions & 2 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import (
)

type Response struct {
responseWriter http.ResponseWriter
headers map[string]string
responseWriter http.ResponseWriter
status int
}

func NewResponse(responseWriter http.ResponseWriter) Response {
Expand Down Expand Up @@ -47,10 +48,18 @@ func (response *Response) GetHeaderOrDefaultValue(key string, defaultValue strin
}

func (response *Response) SetStatus(status int) *Response {
response.responseWriter.WriteHeader(status)
response.status = status
return response
}

func (response *Response) GetStatus() int {
if response.status == 0 {
response.status = http.StatusOK
}

return response.status
}

func (response *Response) Json(data interface{}) *Response {
response.SetHeader("Content-Type", "application/json")

Expand Down
8 changes: 7 additions & 1 deletion response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@ func TestResponse_SetStatus(t *testing.T) {
response.SetResponseWriter(responseWriter).
SetStatus(http.StatusCreated)

assert.Equal(t, http.StatusCreated, responseWriter.Code)
assert.Equal(t, http.StatusCreated, response.GetStatus())
}

func TestResponse_GetStatus_IfNoStatusDefined(t *testing.T) {
response := Response{}

assert.Equal(t, http.StatusOK, response.GetStatus())
}

func TestResponse_Json(t *testing.T) {
Expand Down

0 comments on commit 8cbe521

Please sign in to comment.