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.

46 lines
828 B

4 years ago
4 years ago
4 years ago
  1. package api
  2. import (
  3. "encoding/json"
  4. "git.aiterp.net/lucifer/new-server/models"
  5. "github.com/gin-gonic/gin"
  6. )
  7. var errorMap = map[error]int{
  8. models.ErrInvalidName: 400,
  9. }
  10. type response struct {
  11. Code int `json:"code"`
  12. Message string `json:"message"`
  13. Data interface{} `json:"data"`
  14. }
  15. func handler(fun func(c *gin.Context) (interface{}, error)) gin.HandlerFunc {
  16. return func(c *gin.Context) {
  17. val, err := fun(c)
  18. if err != nil {
  19. errCode := errorMap[err]
  20. if errCode == 0 {
  21. errCode = 500
  22. }
  23. c.JSON(errCode, response{
  24. Code: errCode,
  25. Message: err.Error(),
  26. })
  27. return
  28. }
  29. c.JSON(200, val)
  30. }
  31. }
  32. func parseBody(c *gin.Context, target interface{}) error {
  33. err := json.NewDecoder(c.Request.Body).Decode(target)
  34. if err != nil {
  35. return models.ErrBadInput
  36. }
  37. return nil
  38. }