Skip to content

Commit

Permalink
dev upload static file
Browse files Browse the repository at this point in the history
  • Loading branch information
bvquoc committed Dec 23, 2023
1 parent 3e7db13 commit 6daa2a9
Show file tree
Hide file tree
Showing 16 changed files with 124 additions and 73 deletions.
4 changes: 2 additions & 2 deletions book-store-management-backend/.env
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ PORT=8080
GO_ENV=dev
DEBUG=false

FIREBASE_STORAGE_URI="uit-bookstore-app.appspot.com"
FIREBASE_AUTH_KEY_PATH="/data/private/firebase-auth-key.json"
STATIC_PATH="/data/static"
SERVER_HOST="http://localhost:8080"

DB_USERNAME=root
DB_PASSWORD=123456
Expand Down
27 changes: 22 additions & 5 deletions book-store-management-backend/component/appctx/app_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,28 @@ import (
type AppContext interface {
GetMainDBConnection() *gorm.DB
GetSecretKey() string
GetStaticPath() string
GetServerHost() string
}

type appCtx struct {
db *gorm.DB
secretKey string
db *gorm.DB
secretKey string
staticPath string
serverHost string
}

func NewAppContext(
db *gorm.DB,
secretKey string) *appCtx {
secretKey string,
staticPath string,
serverHost string,
) *appCtx {
return &appCtx{
db: db,
secretKey: secretKey,
db: db,
secretKey: secretKey,
staticPath: staticPath,
serverHost: serverHost,
}
}

Expand All @@ -30,3 +39,11 @@ func (ctx *appCtx) GetMainDBConnection() *gorm.DB {
func (ctx *appCtx) GetSecretKey() string {
return ctx.secretKey
}

func (ctx *appCtx) GetStaticPath() string {
return ctx.staticPath
}

func (ctx *appCtx) GetServerHost() string {
return ctx.serverHost
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package uploadprovider

import (
"book-store-management-backend/common"
"context"
)
import "book-store-management-backend/common"

type UploadProvider interface {
UploadImage(ctx context.Context, data []byte, dst string) (*common.Image, error)
SaveFileUploaded(ctx context.Context, data []byte, dst string) (*common.Image, error)
type UploadStaticProvider interface {
UploadImage(data []byte, path string) (common.Image, error)
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package uploadprovider

import (
"book-store-management-backend/common"
"cloud.google.com/go/storage"
"context"
firebase "firebase.google.com/go/v4"
"google.golang.org/api/option"
"log"
)

type UploadProvider interface {
UploadImage(ctx context.Context, data []byte, dst string) (*common.Image, error)
SaveFileUploaded(ctx context.Context, data []byte, dst string) (*common.Image, error)
}

type firebaseStorageUploadProvider struct {
storageBucketUri string
keyFilePath string
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package uploadprovider

import (
"book-store-management-backend/common"
"os"
"path/filepath"
)

type staticUploadProvider struct {
staticPath string
}

func NewStaticUploadProvider(staticPath string) *staticUploadProvider {
return &staticUploadProvider{
staticPath: staticPath,
}
}

func (provider *staticUploadProvider) UploadImage(data []byte, filename string) (common.Image, error) {
image := common.Image{
CloudName: "local",
Url: "/" + filename,
}

// create file
fullPath := filepath.Join(provider.staticPath, filename)
file, err := os.Create(fullPath)
if err != nil {
return common.Image{}, err // Return the error if file creation fails
}
defer file.Close()

// write data to file
if _, err := file.Write(data); err != nil {
return common.Image{}, err
}

return image, nil
}
4 changes: 2 additions & 2 deletions book-store-management-backend/go-server.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/bin/bash
mkdir -p ./storage
chmod 777 -R ./storage
gin --appPort 8080 --immediate
chmod 777 -R ./storage
gin --appPort 8080 --immediate
24 changes: 12 additions & 12 deletions book-store-management-backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ type appConfig struct {
Port string
Env string

FirebaseStorageUri string
FirebaseKeyPath string
StaticPath string
ServerHost string

DBUsername string
DBPassword string
Expand Down Expand Up @@ -80,7 +80,7 @@ func main() {
db = db.Debug()
}

appCtx := appctx.NewAppContext(db, cfg.SecretKey)
appCtx := appctx.NewAppContext(db, cfg.SecretKey, cfg.StaticPath, cfg.ServerHost)

r := gin.Default()
r.Use(CORSMiddleware())
Expand Down Expand Up @@ -125,15 +125,15 @@ func loadConfig() (*appConfig, error) {
}

return &appConfig{
Port: env["PORT"],
Env: env["GO_ENV"],
FirebaseStorageUri: env["FIREBASE_STORAGE_URI"],
FirebaseKeyPath: env["FIREBASE_AUTH_KEY_PATH"],
DBUsername: env["DB_USERNAME"],
DBPassword: env["DB_PASSWORD"],
DBHost: env["DB_HOST"],
DBDatabase: env["DB_DATABASE"],
SecretKey: env["SECRET_KEY"],
Port: env["PORT"],
Env: env["GO_ENV"],
StaticPath: env["STATIC_PATH"],
ServerHost: env["SERVER_HOST"],
DBUsername: env["DB_USERNAME"],
DBPassword: env["DB_PASSWORD"],
DBHost: env["DB_HOST"],
DBDatabase: env["DB_DATABASE"],
SecretKey: env["SECRET_KEY"],
}, nil
}

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import (
)

func SetupRoutes(router *gin.RouterGroup, appCtx appctx.AppContext) {
staticRouter := router.Group("/static")
staticRouter.Static("", appCtx.GetStaticPath())

uploadFile := router.Group("/upload")
uploadFile.POST("", UploadFile(appCtx))
uploadFile.POST("", UploadFile(appCtx, staticRouter.BasePath()))
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,44 +5,61 @@ import (
"book-store-management-backend/component/appctx"
"book-store-management-backend/component/generator"
"book-store-management-backend/component/uploadprovider"
"fmt"
"github.com/gin-gonic/gin"
"io"
"net/http"
"path/filepath"
)

func UploadFile(appCtx appctx.AppContext) gin.HandlerFunc {
func UploadFile(appCtx appctx.AppContext, r string) gin.HandlerFunc {
return func(c *gin.Context) {
fileHeader, err := c.FormFile("file")

if err != nil {
panic(common.ErrInvalidRequest(err))
}

folder := c.DefaultPostForm("folder", "img")

file, err := fileHeader.Open()
toLocal := c.DefaultPostForm("toLocal", "true")
if toLocal != "true" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Not support upload to cloud yet",
})
return
}

gen := generator.NewShortIdGenerator()
id, err := gen.GenerateId()
if err != nil {
panic(common.ErrInvalidRequest(err))
}
fileName := id + filepath.Ext(fileHeader.Filename)

// Open the uploaded file
file, err := fileHeader.Open()
if err != nil {
panic(common.ErrInvalidRequest(err))
}
defer file.Close()

dataBytes := make([]byte, fileHeader.Size)
if _, err := file.Read(dataBytes); err != nil {
data, err := io.ReadAll(file)
if err != nil {
panic(common.ErrInvalidRequest(err))
}

gen := generator.NewShortIdGenerator()
upP := uploadprovider.NewFirebaseStorageUploadProvider("uit-bookstore-app.appspot.com", "/data/private/firebase-auth-key.json")
picId, err := gen.GenerateId()
staticProvider := uploadprovider.NewStaticUploadProvider(appCtx.GetStaticPath())
res, err := staticProvider.UploadImage(data, fileName)
if err != nil {
panic(err)
panic(common.ErrInvalidRequest(err))
}
res, err := upP.UploadImage(c.Request.Context(), dataBytes, fmt.Sprintf("%s/%s-%s", folder, picId, fileHeader.Filename))
if err != nil {
panic(err)

url := res.Url

if res.CloudName == "local" || res.CloudName == "" || res.Url == "" {
url = appCtx.GetServerHost() + r + res.Url
}
c.JSON(200, common.SimpleSuccessResponse(res))

c.JSON(http.StatusOK, gin.H{
"message": "File uploaded successfully",
"url": url,
})
}
}
13 changes: 0 additions & 13 deletions book-store-management-backend/private/firebase-auth-key.json

This file was deleted.

Empty file.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed book-store-management-backend/static/nct.jpeg
Binary file not shown.
Binary file removed book-store-management-backend/static/tlbt.jpg
Binary file not shown.
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ services:
container_name: bsm-be
volumes:
- ./book-store-management-backend:/data
- ./book-store-management-backend/static:/data/static
- ./bin/gin:/usr/bin/gin
# - $HOME/.aws:/root/.aws
working_dir: /data
Expand Down

0 comments on commit 6daa2a9

Please sign in to comment.