Skip to content

Commit

Permalink
net/http library's consts for representing http codes (#793)
Browse files Browse the repository at this point in the history
* refactor(api): net/http library's consts for representing http codes

* refactor(api,sender,metric_source): http codes

Co-authored-by: m.galimzyanov <[email protected]>
  • Loading branch information
maksgalimz and mgalimzyanov authored Oct 28, 2022
1 parent d33454b commit 426a179
Show file tree
Hide file tree
Showing 8 changed files with 22 additions and 20 deletions.
5 changes: 3 additions & 2 deletions api/controller/contact_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package controller
import (
"errors"
"fmt"
"net/http"
"strings"
"testing"

Expand Down Expand Up @@ -130,7 +131,7 @@ func TestCreateContact(t *testing.T) {
expected := CreateContact(dataBase, contact, userLogin, "")
So(expected, ShouldResemble, &api.ErrorResponse{
ErrorText: err.Error(),
HTTPStatusCode: 500,
HTTPStatusCode: http.StatusInternalServerError,
StatusText: "Internal Server Error",
Err: err,
})
Expand Down Expand Up @@ -202,7 +203,7 @@ func TestCreateContact(t *testing.T) {
expected := CreateContact(dataBase, contact, "", teamID)
So(expected, ShouldResemble, &api.ErrorResponse{
ErrorText: err.Error(),
HTTPStatusCode: 500,
HTTPStatusCode: http.StatusInternalServerError,
StatusText: "Internal Server Error",
Err: err,
})
Expand Down
16 changes: 8 additions & 8 deletions api/error_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func (e *ErrorResponse) Render(w http.ResponseWriter, r *http.Request) error {
func ErrorInternalServer(err error) *ErrorResponse {
return &ErrorResponse{
Err: err,
HTTPStatusCode: 500, //nolint
HTTPStatusCode: http.StatusInternalServerError,
StatusText: "Internal Server Error",
ErrorText: err.Error(),
}
Expand All @@ -36,7 +36,7 @@ func ErrorInternalServer(err error) *ErrorResponse {
func ErrorInvalidRequest(err error) *ErrorResponse {
return &ErrorResponse{
Err: err,
HTTPStatusCode: 400, //nolint
HTTPStatusCode: http.StatusBadRequest,
StatusText: "Invalid request",
ErrorText: err.Error(),
}
Expand All @@ -46,7 +46,7 @@ func ErrorInvalidRequest(err error) *ErrorResponse {
func ErrorRender(err error) *ErrorResponse {
return &ErrorResponse{
Err: err,
HTTPStatusCode: 422, //nolint
HTTPStatusCode: http.StatusUnprocessableEntity,
StatusText: "Error rendering response",
ErrorText: err.Error(),
}
Expand All @@ -55,7 +55,7 @@ func ErrorRender(err error) *ErrorResponse {
// ErrorNotFound return 404 with given error text
func ErrorNotFound(errorText string) *ErrorResponse {
return &ErrorResponse{
HTTPStatusCode: 404, //nolint
HTTPStatusCode: http.StatusNotFound,
StatusText: "Resource not found",
ErrorText: errorText,
}
Expand All @@ -64,7 +64,7 @@ func ErrorNotFound(errorText string) *ErrorResponse {
// ErrorForbidden return 403 with given error text
func ErrorForbidden(errorText string) *ErrorResponse {
return &ErrorResponse{
HTTPStatusCode: 403, //nolint
HTTPStatusCode: http.StatusForbidden,
StatusText: "Forbidden",
ErrorText: errorText,
}
Expand All @@ -74,14 +74,14 @@ func ErrorForbidden(errorText string) *ErrorResponse {
func ErrorRemoteServerUnavailable(err error) *ErrorResponse {
return &ErrorResponse{
Err: err,
HTTPStatusCode: 503, //nolint
HTTPStatusCode: http.StatusServiceUnavailable,
StatusText: "Remote server unavailable.",
ErrorText: fmt.Sprintf("Remote server error, please contact administrator. Raw error: %s", err.Error()),
}
}

// ErrNotFound is default router page not found
var ErrNotFound = &ErrorResponse{HTTPStatusCode: 404, StatusText: "Page not found."} //nolint
var ErrNotFound = &ErrorResponse{HTTPStatusCode: http.StatusNotFound, StatusText: "Page not found."}

// ErrMethodNotAllowed is default 405 router method not allowed
var ErrMethodNotAllowed = &ErrorResponse{HTTPStatusCode: 405, StatusText: "Method not allowed."} //nolint
var ErrMethodNotAllowed = &ErrorResponse{HTTPStatusCode: http.StatusMethodNotAllowed, StatusText: "Method not allowed."}
4 changes: 2 additions & 2 deletions api/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ func NewHandler(db moira.Database, log moira.Logger, index moira.Searcher, confi
func notFoundHandler(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("X-Content-Type-Options", "nosniff")
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(404) //nolint
writer.WriteHeader(http.StatusNotFound)
render.Render(writer, request, api.ErrNotFound) //nolint
}

func methodNotAllowedHandler(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(405) //nolint
writer.WriteHeader(http.StatusMethodNotAllowed)
render.Render(writer, request, api.ErrMethodNotAllowed) //nolint
}
4 changes: 2 additions & 2 deletions api/middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func newLogEntry(logger moira.Logger, request *http.Request) *apiLoggerEntry {

func (entry *apiLoggerEntry) write(status, bytes int, elapsed time.Duration, response http.ResponseWriter) {
if status == 0 {
status = 200
status = http.StatusOK
}
log := entry.logger
log.Int("http.http_status", status)
Expand All @@ -112,7 +112,7 @@ func (entry *apiLoggerEntry) write(status, bytes int, elapsed time.Duration, res
fmt.Fprintf(entry.buf, " %dB", bytes)
entry.buf.WriteString(" in ")
fmt.Fprintf(entry.buf, "%s", elapsed)
if status >= 500 { //nolint
if status >= http.StatusInternalServerError {
errorResponse := getErrorResponseIfItHas(response)
if errorResponse != nil {
fmt.Fprintf(entry.buf, " - Error : %s", errorResponse.ErrorText)
Expand Down
2 changes: 1 addition & 1 deletion metric_source/remote/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func (remote *Remote) makeRequest(req *http.Request) ([]byte, error) {
return body, err
}

if resp.StatusCode != 200 { //nolint
if resp.StatusCode != http.StatusOK {
return body, fmt.Errorf("bad response status %d: %s", resp.StatusCode, string(body))
}

Expand Down
7 changes: 4 additions & 3 deletions senders/msteams/msteams_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package msteams

import (
"net/http"
"testing"
"time"

Expand Down Expand Up @@ -62,7 +63,7 @@ some other text _italic text_`,
defer gock.Off()
gock.New("https://outlook.office.com/webhook/foo").
Post("/").
Reply(200).
Reply(http.StatusOK).
BodyString("1")
contact := moira.ContactData{Value: "https://outlook.office.com/webhook/foo"}
err := sender.SendEvents([]moira.NotificationEvent{event}, contact, trigger, make([][]byte, 0, 1), false)
Expand All @@ -73,7 +74,7 @@ some other text _italic text_`,
defer gock.Off()
gock.New("https://outlook.office.com/webhook/foo").
Post("/").
Reply(200).
Reply(http.StatusOK).
BodyString("Some error")
contact := moira.ContactData{Value: "https://outlook.office.com/webhook/foo"}
err := sender.SendEvents([]moira.NotificationEvent{event}, contact, trigger, make([][]byte, 0, 1), false)
Expand All @@ -84,7 +85,7 @@ some other text _italic text_`,
defer gock.Off()
gock.New("https://outlook.office.com/webhook/foo").
Post("/").
Reply(500).
Reply(http.StatusInternalServerError).
BodyString("Some error")
contact := moira.ContactData{Value: "https://outlook.office.com/webhook/foo"}
err := sender.SendEvents([]moira.NotificationEvent{event}, contact, trigger, make([][]byte, 0, 1), false)
Expand Down
2 changes: 1 addition & 1 deletion senders/victorops/api/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (client *Client) CreateAlert(routingKey string, alert CreateAlertRequest) e
return fmt.Errorf("error while making the request to victorops: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 { //nolint
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("victorops API request resulted in error with status %v: %v", resp.StatusCode, string(body))
}
Expand Down
2 changes: 1 addition & 1 deletion senders/webhook/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,5 @@ func (sender *Sender) SendEvents(events moira.NotificationEvents, contact moira.
}

func isAllowedResponseCode(responseCode int) bool {
return (responseCode >= 200) && (responseCode <= 299)
return (responseCode >= http.StatusOK) && (responseCode < http.StatusMultipleChoices)
}

0 comments on commit 426a179

Please sign in to comment.