api.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package controller
  2. import (
  3. "net/http"
  4. "github.com/mhsanaei/3x-ui/v2/web/service"
  5. "github.com/mhsanaei/3x-ui/v2/web/session"
  6. "github.com/gin-gonic/gin"
  7. )
  8. // APIController handles the main API routes for the 3x-ui panel, including inbounds and server management.
  9. type APIController struct {
  10. BaseController
  11. inboundController *InboundController
  12. serverController *ServerController
  13. Tgbot service.Tgbot
  14. }
  15. // NewAPIController creates a new APIController instance and initializes its routes.
  16. func NewAPIController(g *gin.RouterGroup) *APIController {
  17. a := &APIController{}
  18. a.initRouter(g)
  19. return a
  20. }
  21. // checkAPIAuth is a middleware that returns 404 for unauthenticated API requests
  22. // to hide the existence of API endpoints from unauthorized users
  23. func (a *APIController) checkAPIAuth(c *gin.Context) {
  24. if !session.IsLogin(c) {
  25. c.AbortWithStatus(http.StatusNotFound)
  26. return
  27. }
  28. c.Next()
  29. }
  30. // initRouter sets up the API routes for inbounds, server, and other endpoints.
  31. func (a *APIController) initRouter(g *gin.RouterGroup) {
  32. // Main API group
  33. api := g.Group("/panel/api")
  34. api.Use(a.checkAPIAuth)
  35. // Inbounds API
  36. inbounds := api.Group("/inbounds")
  37. a.inboundController = NewInboundController(inbounds)
  38. // Server API
  39. server := api.Group("/server")
  40. a.serverController = NewServerController(server)
  41. // Extra routes
  42. api.GET("/backuptotgbot", a.BackuptoTgbot)
  43. }
  44. // BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
  45. func (a *APIController) BackuptoTgbot(c *gin.Context) {
  46. a.Tgbot.SendBackupToAdmins()
  47. }