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.
This commit is contained in:
parent
41a4c05801
commit
d3bb03af40
1 changed files with 12 additions and 15 deletions
|
@ -34,6 +34,9 @@ var (
|
||||||
|
|
||||||
ErrAccessDenied = errors.New("access denied")
|
ErrAccessDenied = errors.New("access denied")
|
||||||
ErrUnauthorized = errors.New("unauthorized")
|
ErrUnauthorized = errors.New("unauthorized")
|
||||||
|
// limits for HTTP statuscodes
|
||||||
|
statusMessageMin = 100
|
||||||
|
statusMessageMax = 511
|
||||||
)
|
)
|
||||||
|
|
||||||
var statusCodes = map[int]string{
|
var statusCodes = map[int]string{
|
||||||
|
@ -105,32 +108,26 @@ type MsgResp struct {
|
||||||
Msg string `json:"msg"`
|
Msg string `json:"msg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMsgResp(code int, msg string) (int, interface{}) {
|
// Check if the status code is valid, panic if not.
|
||||||
_, ok := statusCodes[code]
|
func CheckStatusCode(code int){
|
||||||
if !ok {
|
if code < statusMessageMin || code > statusMessageMax {
|
||||||
panic(fmt.Sprintf("status code not found %d", code))
|
panic(fmt.Sprintf("status code not found %d", code))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
func NewMsgResp(code int, msg string) (int, interface{}) {
|
||||||
|
CheckStatusCode(code)
|
||||||
return code, &MsgResp{Msg: msg}
|
return code, &MsgResp{Msg: msg}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Resp(code int) (int, interface{}) {
|
func Resp(code int) (int, interface{}) {
|
||||||
msg, ok := statusCodes[code]
|
CheckStatusCode(code)
|
||||||
if !ok {
|
return code, &MsgResp{Msg: statusCodes[code]}
|
||||||
panic(fmt.Sprintf("status code not found %d", code))
|
|
||||||
}
|
|
||||||
return code, &MsgResp{Msg: msg}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ErrResp(c *gin.Context, code int, err error) (int, interface{}) {
|
func ErrResp(c *gin.Context, code int, err error) (int, interface{}) {
|
||||||
_, ok := statusCodes[code]
|
CheckStatusCode(code)
|
||||||
if !ok {
|
|
||||||
panic(fmt.Sprintf("status code not found %d", code))
|
|
||||||
}
|
|
||||||
gErr := c.Error(err)
|
gErr := c.Error(err)
|
||||||
return code, gErr.JSON()
|
return code, gErr.JSON()
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func FsRootPath(userName, relFilePath string) string {
|
func FsRootPath(userName, relFilePath string) string {
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue