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

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "git.aiterp.net/lucifer/new-server/models"
  6. "github.com/gin-gonic/gin"
  7. "strconv"
  8. )
  9. var errorMap = map[error]int{
  10. models.ErrNotFound: 404,
  11. models.ErrInvalidName: 400,
  12. models.ErrBadInput: 400,
  13. models.ErrBadColor: 400,
  14. models.ErrInternal: 500,
  15. models.ErrUnknownColorFormat: 400,
  16. models.ErrSceneInvalidInterval: 400,
  17. models.ErrSceneNoRoles: 400,
  18. models.ErrSceneRoleNoStates: 400,
  19. models.ErrSceneRoleUnsupportedOrdering: 422,
  20. models.ErrSceneRoleUnknownEffect: 422,
  21. models.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 models.ErrBadInput
  60. }
  61. return nil
  62. }
  63. func ctxOf(c *gin.Context) context.Context {
  64. return c.Request.Context()
  65. }