105 lines
2.4 KiB
Go
105 lines
2.4 KiB
Go
package handler
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"github.com/xuri/excelize/v2"
|
|
"gitstore.ru/tolikproh/sirius/internal/model"
|
|
)
|
|
|
|
func GinConvert(c *gin.Context) {
|
|
file, err := c.FormFile("file")
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
}
|
|
|
|
fileUuid := uuid.New().String()
|
|
fileUpload := "./upload/" + fileUuid + "_" + file.Filename
|
|
// сохраняем загруженный файл в /tmp
|
|
err = c.SaveUploadedFile(file, fileUpload)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
var sirius model.Sirius
|
|
siriusJson, err := ioutil.ReadFile(fileUpload)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": errors.New("No read file").Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
siriusJson = bytes.TrimPrefix(siriusJson, []byte("\xef\xbb\xbf"))
|
|
|
|
if !json.Valid(siriusJson) {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": errors.New("Formated file not supported").Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
err = json.Unmarshal(siriusJson, &sirius)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": errors.New("Error unmarshal file").Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
fileConverted := "./convert/" + fileUuid + ".xlsx"
|
|
if err := SaveToExel(fileConverted, sirius.NewBolid().ZoneInfo()); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": errors.New("Error create file").Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
siriusExel, err := ioutil.ReadFile(fileConverted)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": errors.New("No read file exel").Error(),
|
|
})
|
|
return
|
|
}
|
|
c.Data(200, "application/vnd.ms-excel", siriusExel)
|
|
|
|
}
|
|
|
|
func SaveToExel(filename string, data []model.ZoneInfo) error {
|
|
f := excelize.NewFile()
|
|
defer func() {
|
|
if err := f.Close(); err != nil {
|
|
return
|
|
}
|
|
}()
|
|
// Create a new sheet.
|
|
f.SetCellValue("Sheet1", "A2", "№ зоны")
|
|
f.SetCellValue("Sheet1", "B2", "Описание зоны")
|
|
f.SetCellValue("Sheet1", "C2", "Адреса в зоне")
|
|
i := 3
|
|
for _, d := range data {
|
|
f.SetCellValue("Sheet1", "A"+strconv.Itoa(i), d.ZoneNum)
|
|
f.SetCellValue("Sheet1", "B"+strconv.Itoa(i), d.ZoneName)
|
|
f.SetCellValue("Sheet1", "C"+strconv.Itoa(i), d.InputString())
|
|
i++
|
|
}
|
|
// Save spreadsheet by the given path.
|
|
if err := f.SaveAs(filename); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|