amocrm/internal/server/http/http.go

67 lines
1.1 KiB
Go
Raw Normal View History

2024-04-04 09:42:40 +00:00
package http
import (
"context"
"fmt"
"github.com/gofiber/fiber/v2"
2024-04-19 16:14:06 +00:00
"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/middleware"
2024-04-04 09:42:40 +00:00
)
type ServerConfig struct {
Controllers []Controller
}
type Server struct {
Controllers []Controller
app *fiber.App
}
func NewServer(config ServerConfig) *Server {
app := fiber.New()
2024-04-19 16:14:06 +00:00
app.Use(middleware.JWTAuth())
2024-05-14 20:13:13 +00:00
app.Use("/webhook", func(c *fiber.Ctx) error {
return c.Next()
})
2024-04-04 09:42:40 +00:00
s := &Server{
Controllers: config.Controllers,
app: app,
}
s.registerRoutes()
return s
}
func (s *Server) Start(addr string) error {
if err := s.app.Listen(addr); err != nil {
return err
}
return nil
}
func (s *Server) Shutdown(ctx context.Context) error {
return s.app.Shutdown()
}
func (s *Server) registerRoutes() {
for _, c := range s.Controllers {
router := s.app.Group(c.Name())
c.Register(router)
}
}
type Controller interface {
Register(router fiber.Router)
Name() string
}
func (s *Server) ListRoutes() {
fmt.Println("Registered routes:")
for _, stack := range s.app.Stack() {
for _, route := range stack {
fmt.Printf("%s %s\n", route.Method, route.Path)
}
}
}