response.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package response
  2. import (
  3. "github.com/360EntSecGroup-Skylar/excelize"
  4. "github.com/gin-gonic/gin"
  5. "net/http"
  6. "strconv"
  7. )
  8. type Response struct {
  9. Code int `json:"code"`
  10. Data interface{} `json:"data"`
  11. Msg string `json:"msg"`
  12. }
  13. const (
  14. ERROR = 7
  15. SUCCESS = 0
  16. )
  17. func Result(code int, data interface{}, msg string, c *gin.Context) {
  18. // 开始时间
  19. c.JSON(http.StatusOK, Response{
  20. code,
  21. data,
  22. msg,
  23. })
  24. }
  25. func Ok(c *gin.Context) {
  26. Result(SUCCESS, map[string]interface{}{}, "操作成功", c)
  27. }
  28. func OkWithMessage(message string, c *gin.Context) {
  29. Result(SUCCESS, map[string]interface{}{}, message, c)
  30. }
  31. func OkWithData(data interface{}, c *gin.Context) {
  32. Result(SUCCESS, data, "操作成功", c)
  33. }
  34. func OkDetailed(data interface{}, message string, c *gin.Context) {
  35. Result(SUCCESS, data, message, c)
  36. }
  37. func OkWithXlsx(list []interface{}, title []string, fileName string, c *gin.Context) {
  38. file := excelize.NewFile()
  39. file.SetSheetRow("Sheet1", "A1", &title)
  40. for i, v := range list {
  41. // 第一行被title占用
  42. lint := strconv.Itoa(i + 2)
  43. file.SetSheetRow("Sheet1", "A"+lint, v)
  44. }
  45. c.Header("Content-Type", "application/octet-stream")
  46. c.Header("Content-Disposition", "attachment; filename="+fileName)
  47. c.Header("Content-Transfer-Encoding", "binary")
  48. _ = file.Write(c.Writer)
  49. }
  50. func Fail(c *gin.Context) {
  51. Result(ERROR, map[string]interface{}{}, "操作失败", c)
  52. }
  53. func FailWithMessage(message string, c *gin.Context) {
  54. Result(ERROR, map[string]interface{}{}, message, c)
  55. }
  56. func FailWithDetailed(code int, data interface{}, message string, c *gin.Context) {
  57. Result(code, data, message, c)
  58. }