sirius/internal/controller/handler/handler.go

76 lines
1.9 KiB
Go
Raw Permalink Normal View History

2023-04-17 08:48:09 +03:00
package handler
import (
2023-04-28 02:35:30 +03:00
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
2023-04-17 08:48:09 +03:00
"gitstore.ru/tolikproh/sirius/internal/model"
2023-04-28 02:35:30 +03:00
"gitstore.ru/tolikproh/sirius/internal/service"
2023-04-17 08:48:09 +03:00
)
type Handler struct {
log *logrus.Logger
cfg *model.Config
2023-04-17 08:48:09 +03:00
}
2023-04-28 02:35:30 +03:00
var (
TEXT_TYPES = map[string]interface{}{
"text/plain; charset=utf-8": nil,
}
)
func New(cfg *model.Config, log *logrus.Logger) *Handler {
// HTTP Server
return &Handler{cfg: cfg, log: log}
2023-04-17 08:48:09 +03:00
}
2023-04-28 02:35:30 +03:00
func (s *Handler) GinConvert(c *gin.Context) {
sessionId := uuid.New().String()
s.log.Printf("start convert. session id: %s; user agent: %s; remote addr: %s; file size [byte]: %d",
sessionId, c.Request.UserAgent(), c.Request.RemoteAddr, c.Request.ContentLength)
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, s.cfg.Srv.MaxSizeFile<<20)
file, fileHeader, err := c.Request.FormFile("file")
if err != nil {
s.log.Errorf("session id: %s. error code: 001. %s", sessionId, err.Error())
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
defer file.Close()
buffer := make([]byte, fileHeader.Size)
file.Read(buffer)
fileType := http.DetectContentType(buffer)
// Validate File Type
if _, ex := TEXT_TYPES[fileType]; !ex {
s.log.Errorf("session id: %s. error code: 002. formated data not text/plain", sessionId)
c.JSON(http.StatusBadRequest, gin.H{
"error": errors.New("formated data not text/plain").Error(),
})
return
}
respBuff, err := service.SiriusConv(buffer)
if err != nil {
s.log.Errorf("session id: %s. error code: 004. %s", sessionId, err.Error())
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
c.Data(200, "application/vnd.ms-excel", respBuff.Bytes())
s.log.Printf("session id: %s.converted: ok. filename: %s; file size: %d bytes", sessionId, fileHeader.Filename, fileHeader.Size)
}