From 69c1cd3f381b19b988a6af51a8e38303f216b001 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sat, 1 Dec 2018 21:41:30 -0500 Subject: routes/api: change status handle to new style Also fixed one bug that did not catch team not found error. --- pkg/context/api.go | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) (limited to 'pkg/context/api.go') diff --git a/pkg/context/api.go b/pkg/context/api.go index fab66024..7df5b23a 100644 --- a/pkg/context/api.go +++ b/pkg/context/api.go @@ -6,6 +6,7 @@ package context import ( "fmt" + "net/http" "strings" "github.com/Unknwon/paginater" @@ -33,7 +34,7 @@ func (c *APIContext) Error(status int, title string, obj interface{}) { message = obj.(string) } - if status == 500 { + if status == http.StatusInternalServerError { log.Error(3, "%s: %s", title, message) } @@ -43,6 +44,27 @@ func (c *APIContext) Error(status int, title string, obj interface{}) { }) } +// NotFound renders the 404 response. +func (c *APIContext) NotFound() { + c.Status(http.StatusNotFound) +} + +// ServerError renders the 500 response. +func (c *APIContext) ServerError(title string, err error) { + c.Error(http.StatusInternalServerError, title, err) +} + +// NotFoundOrServerError use error check function to determine if the error +// is about not found. It responses with 404 status code for not found error, +// or error context description for logging purpose of 500 server error. +func (c *APIContext) NotFoundOrServerError(title string, errck func(error) bool, err error) { + if errck(err) { + c.NotFound() + return + } + c.ServerError(title, err) +} + // SetLinkHeader sets pagination link header by given total number and page size. func (c *APIContext) SetLinkHeader(total, pageSize int) { page := paginater.New(total, pageSize, c.QueryInt("page"), 0) -- cgit v1.2.3