87 lines
2.2 KiB
Go
87 lines
2.2 KiB
Go
package chat
|
|
|
|
import (
|
|
"log"
|
|
"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 {
|
|
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 = 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(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
|
|
HandleError: true,
|
|
LogLatency: true,
|
|
LogMethod: true,
|
|
LogRoutePath: true,
|
|
LogURIPath: true,
|
|
LogRequestID: true,
|
|
LogStatus: true,
|
|
LogResponseSize: true,
|
|
LogValuesFunc: func(_ echo.Context, values middleware.RequestLoggerValues) error {
|
|
path := values.RoutePath
|
|
if path == "" {
|
|
path = values.URIPath
|
|
}
|
|
log.Printf(
|
|
"request_id=%s method=%s path=%s status=%d response_bytes=%d latency=%s",
|
|
values.RequestID, values.Method, path, values.Status, values.ResponseSize, values.Latency,
|
|
)
|
|
return nil
|
|
},
|
|
}))
|
|
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)
|
|
|
|
return e
|
|
}
|