Implement channel handler and simplify the main function

This commit is contained in:
2026-03-09 10:44:00 +03:30
parent c6a7fc4676
commit b6771fe6dd
4 changed files with 55 additions and 15 deletions
+5 -10
View File
@@ -1,13 +1,11 @@
package main
import (
"context"
"log"
"tgss/internal/config"
"tgss/internal/handlers"
"tgss/internal/infra"
"tgss/internal/server"
"tgss/internal/telegram"
"time"
"go.uber.org/fx"
)
@@ -18,16 +16,13 @@ func main() {
infra.NewLogger,
config.Load,
server.NewGin,
handlers.NewChannelHandler,
),
telegram.Module,
fx.Invoke(server.RegisterRoutes),
fx.Logger(infra.NewFXLogger()),
)
startCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := app.Start(startCtx); err != nil {
log.Fatalf("failed to start: %v", err)
}
app.Wait()
app.Run()
}
+36 -1
View File
@@ -1 +1,36 @@
package handlers
package handlers
import (
"context"
"tgss/internal/telegram"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
type ChannelHandler struct {
logger *zap.Logger
tgService *telegram.Service
}
func NewChannelHandler(
tgService *telegram.Service,
logger *zap.Logger,
) *ChannelHandler {
return &ChannelHandler{
logger: logger,
tgService: tgService,
}
}
func (ch *ChannelHandler) GetLatestMessages(c *gin.Context) {
chennelId := c.Param("id")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
m, err := ch.tgService.LastMessages(ctx, chennelId, 10)
if err != nil {
ch.logger.Error("Error getting channel messages:", zap.Error(err))
}
c.JSON(200, m)
}
+10 -4
View File
@@ -2,6 +2,7 @@ package server
import (
"context"
"tgss/internal/handlers"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
@@ -15,15 +16,17 @@ type RouterParams struct {
Lifecycle fx.Lifecycle
GinEngine *gin.Engine
Logger *zap.Logger
ChannelHandler *handlers.ChannelHandler
}
func NewGin() *gin.Engine {
g := gin.New()
g.Use(gin.Recovery())
g.Use(cors.New(cors.Config{
AllowAllOrigins: true,
AllowMethods: []string{"GET"},
AllowHeaders: []string{"Origin", "Content-Type"},
AllowAllOrigins: true,
AllowMethods: []string{"GET"},
AllowHeaders: []string{"Origin", "Content-Type"},
}))
return g
}
@@ -36,8 +39,11 @@ func RegisterRoutes(params RouterParams) {
"message": "pong",
})
})
params.GinEngine.GET("/channel/:id", params.ChannelHandler.GetLatestMessages)
params.Logger.Info("Starting server")
go params.GinEngine.Run(":8080")
go params.GinEngine.Run(":3000")
params.Logger.Info("Server is running on port 8080")
return nil
},
+4
View File
@@ -5,6 +5,7 @@ import (
"net"
"net/url"
"tgss/internal/config"
"time"
"github.com/gotd/td/session"
"github.com/gotd/td/telegram"
@@ -20,6 +21,9 @@ func NewTelegramClient(cfg *config.Config, logger *zap.Logger) *telegram.Client
DCList: dcs.Prod(),
Logger: logger,
SessionStorage: &session.FileStorage{Path: cfg.SessionPath},
DialTimeout: 20*time.Second,
ExchangeTimeout: 20*time.Second,
MigrationTimeout: 20*time.Second,
}
if cfg.ProxyURL != "" {