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.

70 lines
1.3 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. }
  17. type response struct {
  18. Code int `json:"code"`
  19. Message string `json:"message"`
  20. Data interface{} `json:"data"`
  21. }
  22. func handler(fun func(c *gin.Context) (interface{}, error)) gin.HandlerFunc {
  23. return func(c *gin.Context) {
  24. val, err := fun(c)
  25. if err != nil {
  26. errCode := errorMap[err]
  27. if errCode == 0 {
  28. errCode = 500
  29. }
  30. c.JSON(errCode, response{
  31. Code: errCode,
  32. Message: err.Error(),
  33. })
  34. return
  35. }
  36. c.JSON(200, response{
  37. Code: 200,
  38. Message: "success",
  39. Data: val,
  40. })
  41. }
  42. }
  43. func intParam(c *gin.Context, key string) int {
  44. i, err := strconv.Atoi(c.Param(key))
  45. if err != nil {
  46. return 0
  47. }
  48. return i
  49. }
  50. func parseBody(c *gin.Context, target interface{}) error {
  51. err := json.NewDecoder(c.Request.Body).Decode(target)
  52. if err != nil {
  53. return models.ErrBadInput
  54. }
  55. return nil
  56. }
  57. func ctxOf(c *gin.Context) context.Context {
  58. return c.Request.Context()
  59. }