v0.0.5 Добавлена логика создания поста и загрузки изображения

This commit is contained in:
madipo2611 2025-05-06 01:10:36 +03:00
parent 95bdb56e70
commit 1fd284afaf
4 changed files with 49 additions and 1 deletions

View File

@ -2,9 +2,15 @@ package service
import (
"context"
"encoding/base64"
"errors"
"fmt"
"log"
"os"
"strings"
"tailly_back_v2/internal/domain"
"tailly_back_v2/internal/repository"
"tailly_back_v2/internal/utils"
"time"
)
@ -30,6 +36,9 @@ func NewPostService(postRepo repository.PostRepository) PostService {
// Создание нового поста
func (s *postService) Create(ctx context.Context, authorID int, title, content string) (*domain.Post, error) {
const op = "service/postService.Create"
// Валидация данных
if title == "" {
return nil, errors.New("post title cannot be empty")
@ -38,9 +47,36 @@ func (s *postService) Create(ctx context.Context, authorID int, title, content s
return nil, errors.New("post content cannot be empty")
}
if strings.HasPrefix(content, "data:image/jpeg;base64,") {
content = strings.TrimPrefix(content, "data:image/jpeg;base64,")
}
imgBase64, err := base64.StdEncoding.DecodeString(content)
if err != nil {
log.Println("failed to decode image base64", op, err)
return nil, err
}
randName := utils.GenerateId()
upPath := fmt.Sprintf("./uploads/posts/images/%d", authorID)
err = os.MkdirAll(upPath, os.ModePerm)
if err != nil {
log.Println("failed to create directory", op, err)
return nil, err
}
fileName := fmt.Sprintf("%s/%s.jpg", upPath, randName)
err = os.WriteFile(fileName, imgBase64, os.ModePerm)
if err != nil {
log.Println("failed to write file", op, err)
return nil, err
}
post := &domain.Post{
Title: title,
Content: content,
Content: fileName,
AuthorID: authorID,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),

View File

@ -0,0 +1,12 @@
package utils
import (
"crypto/rand"
"fmt"
)
func GenerateId() string {
b := make([]byte, 16)
rand.Read(b)
return fmt.Sprintf("%x", b)
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 430 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 496 KiB