forked from mtusi2026/mtusi2026lab6
77 lines
2.1 KiB
Go
77 lines
2.1 KiB
Go
package chat
|
|
|
|
import (
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability"
|
|
"os"
|
|
"sync/atomic"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/labstack/echo/v4/middleware"
|
|
"github.com/swaggest/swgui/v5emb"
|
|
)
|
|
|
|
// Chat is the HTTP handler and depends only on the application boundary.
|
|
type Chat struct {
|
|
attachments *attachment.Service
|
|
instanceID string
|
|
draining atomic.Bool
|
|
useCase UseCase
|
|
cursor cursorCodec
|
|
}
|
|
|
|
func NewChat(useCase UseCase, cursorKey [32]byte) *Chat {
|
|
instanceID := os.Getenv("INSTANCE_ID")
|
|
if instanceID == "" {
|
|
instanceID, _ = os.Hostname()
|
|
}
|
|
if instanceID == "" {
|
|
instanceID = uuid.NewString()
|
|
}
|
|
return &Chat{useCase: useCase, cursor: cursorCodec{secret: cursorKey}, instanceID: instanceID}
|
|
}
|
|
|
|
func (h *Chat) Drain() { h.draining.Store(true) }
|
|
|
|
func (h *Chat) Router() *echo.Echo {
|
|
e := echo.New()
|
|
e.HideBanner = true
|
|
e.HidePort = true
|
|
e.HTTPErrorHandler = h.httpErrorHandler
|
|
e.Use(h.requestIDMiddleware)
|
|
e.Use(observability.Middleware)
|
|
e.Use(middleware.Recover())
|
|
|
|
e.GET("/health/live", h.liveness)
|
|
e.GET("/health/ready", h.readiness)
|
|
swaggerUI := echo.WrapHandler(v5emb.New(
|
|
"MTUSI Messenger",
|
|
"/swagger/openapi.json",
|
|
"/swagger/",
|
|
))
|
|
e.GET("/swagger", h.swagger)
|
|
e.GET("/swagger/", swaggerUI)
|
|
e.GET("/swagger/openapi.json", h.swaggerSpec)
|
|
e.GET("/swagger/*", swaggerUI)
|
|
e.POST("/api/v1/users", h.createUser)
|
|
|
|
e.POST("/api/v1/auth/sessions", h.createSession)
|
|
|
|
api := e.Group("/api/v1", h.authenticate)
|
|
api.GET("/users/me", h.currentUser)
|
|
api.DELETE("/auth/sessions/current", h.deleteSession)
|
|
api.POST("/chats", h.createChat)
|
|
api.GET("/chats", h.listChats)
|
|
api.GET("/chats/:chat_id", h.getChat)
|
|
api.POST("/chats/:chat_id/messages", h.createMessage)
|
|
api.GET("/chats/:chat_id/messages", h.listMessages)
|
|
if h.attachments != nil {
|
|
api.POST("/chats/:chat_id/attachments", h.uploadAttachment)
|
|
api.GET("/attachments/:attachment_id", h.getAttachment)
|
|
api.GET("/attachments/:attachment_id/content", h.attachmentContent)
|
|
}
|
|
|
|
return e
|
|
}
|