From d3bb03af40608bdc261714ab2c7d93550fb5708c Mon Sep 17 00:00:00 2001 From: Youssef Eddaif <63888397+unrealjo@users.noreply.github.com> Date: Sat, 29 Jul 2023 23:19:21 +0100 Subject: [PATCH] chore(heandlers/util): refactor response methods Changes: - The repeated code that checks if the status code is valid has been moved into a separate function to avoid duplication. - Rather than looking up the status code from a map, you can check if the code is a valid HTTP status code directly. --- src/handlers/util.go | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/handlers/util.go b/src/handlers/util.go index ecf9d86..aace5b8 100644 --- a/src/handlers/util.go +++ b/src/handlers/util.go @@ -34,6 +34,9 @@ var ( ErrAccessDenied = errors.New("access denied") ErrUnauthorized = errors.New("unauthorized") + // limits for HTTP statuscodes + statusMessageMin = 100 + statusMessageMax = 511 ) var statusCodes = map[int]string{ @@ -105,32 +108,26 @@ type MsgResp struct { Msg string `json:"msg"` } -func NewMsgResp(code int, msg string) (int, interface{}) { - _, ok := statusCodes[code] - if !ok { +// Check if the status code is valid, panic if not. +func CheckStatusCode(code int){ + if code < statusMessageMin || code > statusMessageMax { panic(fmt.Sprintf("status code not found %d", code)) } +} +func NewMsgResp(code int, msg string) (int, interface{}) { + CheckStatusCode(code) return code, &MsgResp{Msg: msg} - } func Resp(code int) (int, interface{}) { - msg, ok := statusCodes[code] - if !ok { - panic(fmt.Sprintf("status code not found %d", code)) - } - return code, &MsgResp{Msg: msg} - + CheckStatusCode(code) + return code, &MsgResp{Msg: statusCodes[code]} } func ErrResp(c *gin.Context, code int, err error) (int, interface{}) { - _, ok := statusCodes[code] - if !ok { - panic(fmt.Sprintf("status code not found %d", code)) - } + CheckStatusCode(code) gErr := c.Error(err) return code, gErr.JSON() - } func FsRootPath(userName, relFilePath string) string {