You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
1.6 KiB
77 lines
1.6 KiB
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"git.aiterp.net/lucifer/new-server/internal/lerrors"
|
|
"github.com/gin-gonic/gin"
|
|
"strconv"
|
|
)
|
|
|
|
var errorMap = map[error]int{
|
|
lerrors.ErrNotFound: 404,
|
|
lerrors.ErrInvalidName: 400,
|
|
lerrors.ErrBadInput: 400,
|
|
lerrors.ErrBadColor: 400,
|
|
lerrors.ErrInternal: 500,
|
|
lerrors.ErrUnknownColorFormat: 400,
|
|
|
|
lerrors.ErrSceneInvalidInterval: 400,
|
|
lerrors.ErrSceneNoRoles: 400,
|
|
lerrors.ErrSceneRoleNoStates: 400,
|
|
lerrors.ErrSceneRoleUnsupportedOrdering: 422,
|
|
lerrors.ErrSceneRoleUnknownEffect: 422,
|
|
lerrors.ErrSceneRoleUnknownPowerMode: 422,
|
|
}
|
|
|
|
type response struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data interface{} `json:"data"`
|
|
}
|
|
|
|
func handler(fun func(c *gin.Context) (interface{}, error)) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
val, err := fun(c)
|
|
if err != nil {
|
|
errCode := errorMap[err]
|
|
if errCode == 0 {
|
|
errCode = 500
|
|
}
|
|
|
|
c.JSON(errCode, response{
|
|
Code: errCode,
|
|
Message: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
c.JSON(200, response{
|
|
Code: 200,
|
|
Message: "success",
|
|
Data: val,
|
|
})
|
|
}
|
|
}
|
|
|
|
func intParam(c *gin.Context, key string) int {
|
|
i, err := strconv.Atoi(c.Param(key))
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
|
|
return i
|
|
}
|
|
|
|
func parseBody(c *gin.Context, target interface{}) error {
|
|
err := json.NewDecoder(c.Request.Body).Decode(target)
|
|
if err != nil {
|
|
return lerrors.ErrBadInput
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func ctxOf(c *gin.Context) context.Context {
|
|
return c.Request.Context()
|
|
}
|