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

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "git.aiterp.net/lucifer/new-server/internal/lerrors"
  6. "github.com/gin-gonic/gin"
  7. "strconv"
  8. )
  9. var errorMap = map[error]int{
  10. lerrors.ErrNotFound: 404,
  11. lerrors.ErrInvalidName: 400,
  12. lerrors.ErrBadInput: 400,
  13. lerrors.ErrBadColor: 400,
  14. lerrors.ErrInternal: 500,
  15. lerrors.ErrUnknownColorFormat: 400,
  16. lerrors.ErrSceneInvalidInterval: 400,
  17. lerrors.ErrSceneNoRoles: 400,
  18. lerrors.ErrSceneRoleNoStates: 400,
  19. lerrors.ErrSceneRoleUnsupportedOrdering: 422,
  20. lerrors.ErrSceneRoleUnknownEffect: 422,
  21. lerrors.ErrSceneRoleUnknownPowerMode: 422,
  22. }
  23. type response struct {
  24. Code int `json:"code"`
  25. Message string `json:"message"`
  26. Data interface{} `json:"data"`
  27. }
  28. func handler(fun func(c *gin.Context) (interface{}, error)) gin.HandlerFunc {
  29. return func(c *gin.Context) {
  30. val, err := fun(c)
  31. if err != nil {
  32. errCode := errorMap[err]
  33. if errCode == 0 {
  34. errCode = 500
  35. }
  36. c.JSON(errCode, response{
  37. Code: errCode,
  38. Message: err.Error(),
  39. })
  40. return
  41. }
  42. c.JSON(200, response{
  43. Code: 200,
  44. Message: "success",
  45. Data: val,
  46. })
  47. }
  48. }
  49. func intParam(c *gin.Context, key string) int {
  50. i, err := strconv.Atoi(c.Param(key))
  51. if err != nil {
  52. return 0
  53. }
  54. return i
  55. }
  56. func parseBody(c *gin.Context, target interface{}) error {
  57. err := json.NewDecoder(c.Request.Body).Decode(target)
  58. if err != nil {
  59. return lerrors.ErrBadInput
  60. }
  61. return nil
  62. }
  63. func ctxOf(c *gin.Context) context.Context {
  64. return c.Request.Context()
  65. }