152 lines
4.1 KiB
Go
152 lines
4.1 KiB
Go
package main
|
||
|
||
import (
|
||
configcore "bitrix_balancer_api/core/config"
|
||
clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers"
|
||
"errors"
|
||
"fmt"
|
||
"log"
|
||
"net/http"
|
||
"rest_telephony_service/handlers/telephony"
|
||
typesm "rest_telephony_service/types"
|
||
"time"
|
||
|
||
"github.com/go-chi/chi/v5"
|
||
"github.com/go-chi/chi/v5/middleware"
|
||
"github.com/go-chi/cors"
|
||
"github.com/go-chi/httprate"
|
||
"github.com/sirupsen/logrus"
|
||
)
|
||
|
||
const (
|
||
readTimeout = 15 * time.Minute
|
||
writeTimeout = 15 * time.Minute
|
||
idleTimeout = 15 * time.Minute
|
||
rateLimit = 50
|
||
rateWindow = 1 * time.Second
|
||
)
|
||
|
||
func main() {
|
||
err := initService()
|
||
if err != nil {
|
||
logrus.Errorln("🔴 failed to init common: ", err)
|
||
}
|
||
select {} // блокируем завершение горутины
|
||
}
|
||
|
||
func initService() error {
|
||
clientsExternal, err := getClientsExternal()
|
||
if err != nil {
|
||
logrus.Errorln("🔴 failed to load config: ", err)
|
||
return err
|
||
}
|
||
|
||
ipc, err := initInternalProvider(clientsExternal)
|
||
if err != nil {
|
||
logrus.Errorln("🔴 failed to init internal provider: ", err)
|
||
return err
|
||
}
|
||
|
||
router, err := initBaseApiRouter(ipc)
|
||
if err != nil {
|
||
logrus.Errorln("🔴 failed to init base api router: ", err)
|
||
return err
|
||
}
|
||
|
||
if err := startRestApiServer(ipc, router); err != nil {
|
||
logrus.Errorln("🔴 failed to start server: ", err)
|
||
return err
|
||
}
|
||
|
||
return nil
|
||
}
|
||
|
||
func getClientsExternal() (clientcontrollers.ClientsExternal, error) {
|
||
options := &configcore.ConfigLoadOptions{
|
||
Redis: true,
|
||
Database: true,
|
||
Server: configcore.ExposedServiceOptions{
|
||
RESTBaseService: true, // Берем конфиг для портов из базы
|
||
},
|
||
}
|
||
|
||
return clientcontrollers.ReturnClientsExternal(options)
|
||
}
|
||
|
||
func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*typesm.InternalProviderControl, error) {
|
||
return &typesm.InternalProviderControl{
|
||
Config: clientsExternal.Config,
|
||
RedisClient: clientsExternal.Redis,
|
||
Database: clientsExternal.DB,
|
||
TGBotClient: clientsExternal.Telegram,
|
||
}, nil
|
||
}
|
||
|
||
func startRestApiServer(ipc *typesm.InternalProviderControl, router *chi.Mux) error {
|
||
// Допустим, телефония живет на порту 15002. В будущем вынесем в config.yml
|
||
serverPort := "15002"
|
||
|
||
serverAddr := ":" + serverPort
|
||
httpServer := &http.Server{
|
||
Addr: serverAddr,
|
||
Handler: router,
|
||
ReadTimeout: readTimeout,
|
||
WriteTimeout: writeTimeout,
|
||
IdleTimeout: idleTimeout,
|
||
}
|
||
|
||
log.Printf("✅ Starting Telephony server on %s", serverAddr)
|
||
return httpServer.ListenAndServe()
|
||
}
|
||
|
||
func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) {
|
||
router := chi.NewRouter()
|
||
corsOptions := cors.New(cors.Options{
|
||
AllowedOrigins: []string{"*"},
|
||
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodOptions},
|
||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id"},
|
||
ExposedHeaders: []string{"Link", "Cache-Control"},
|
||
AllowCredentials: true,
|
||
MaxAge: 300,
|
||
})
|
||
|
||
router.Use(corsOptions.Handler)
|
||
router.Use(middleware.RealIP)
|
||
router.Use(middleware.Recoverer)
|
||
router.Use(httprate.LimitByIP(rateLimit, rateWindow))
|
||
|
||
if ipc.Database == nil {
|
||
return nil, errors.New("failed_to_connect_db")
|
||
}
|
||
|
||
err := registerRoutes(router, ipc)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
return router, nil
|
||
}
|
||
|
||
// регистрирует маршруты
|
||
func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) error {
|
||
// Подключаем наши маршруты
|
||
if err := telephony.RegisterTelephonyRoutes(router, ipc); err != nil {
|
||
return errors.New(fmt.Sprintf("🔴 failed to register telephony routes: %v", err))
|
||
}
|
||
|
||
// Вывод зарегистрированных маршрутов
|
||
if err := printRoutes(router, ipc); err != nil {
|
||
return errors.New(fmt.Sprintf("🔴 failed to print routes: %v", err))
|
||
}
|
||
|
||
return nil
|
||
}
|
||
|
||
func printRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
|
||
err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
|
||
logrus.Info(fmt.Sprintf("🩵 [ %s ] %s\n", method, route))
|
||
return nil
|
||
})
|
||
return err
|
||
}
|