routes.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package routes
  2. import (
  3. // "fwh-toolbox-server/controllers"
  4. _ "fwh-toolbox-server/docs"
  5. "time"
  6. "github.com/gofiber/fiber/v2"
  7. "github.com/gofiber/swagger"
  8. "github.com/google/uuid"
  9. )
  10. const traceIdHeader string = "X-Trace-Id"
  11. type Response[T any] struct {
  12. Code int `json:"code"`
  13. Message string `json:"message"`
  14. Data T `json:"data"`
  15. TraceID string `json:"traceId"`
  16. Timestamp int64 `json:"timestamp"`
  17. }
  18. type ResponseNoData struct {
  19. Code int `json:"code"`
  20. Message string `json:"message"`
  21. TraceID string `json:"traceId"`
  22. Timestamp int64 `json:"timestamp"`
  23. }
  24. func JSONResponse[T any](c *fiber.Ctx, code int, message string, data T) error {
  25. traceId := c.Get(traceIdHeader) // 从请求头取
  26. if traceId == "" {
  27. traceId = uuid.New().String() // 没有就生成
  28. }
  29. // 设置到响应头,让前端也能拿到
  30. c.Set(traceIdHeader, traceId)
  31. resp := Response[T]{
  32. Code: code,
  33. Message: message,
  34. Data: data,
  35. TraceID: traceId,
  36. Timestamp: time.Now().UnixMilli(),
  37. }
  38. return c.JSON(resp)
  39. }
  40. func JSONResponseNoData(c *fiber.Ctx, code int, message string) error {
  41. traceId := c.Get(traceIdHeader) // 从请求头取
  42. if traceId == "" {
  43. traceId = uuid.New().String() // 没有就生成
  44. }
  45. // 设置到响应头,让前端也能拿到
  46. c.Set(traceIdHeader, traceId)
  47. resp := ResponseNoData{
  48. Code: code,
  49. Message: message,
  50. TraceID: traceId,
  51. Timestamp: time.Now().UnixMilli(),
  52. }
  53. return c.JSON(resp)
  54. }
  55. func Setup(app *fiber.App) {
  56. api := app.Group("/api")
  57. // api.Get("/keyAccounts/sunrun/state", controllers.GetUsers)
  58. // api.Get("/keyAccounts/sunrun/abnormalList", controllers.GetUsers)
  59. // …
  60. SitesMonitorSetup(api)
  61. SitesAnalysisSetup(api)
  62. app.Get("/swagger/*", swagger.HandlerDefault)
  63. }