migrate to fiber

This commit is contained in:
Zoe
2024-10-01 03:45:43 -05:00
parent e39e5f51fd
commit e64b9fba7f
17 changed files with 587 additions and 372 deletions

View File

@@ -2,6 +2,7 @@ package routes
import (
"context"
"filething/db"
"filething/models"
"fmt"
"net/http"
@@ -12,24 +13,23 @@ import (
"time"
"github.com/dustin/go-humanize"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/uptrace/bun"
"golang.org/x/crypto/bcrypt"
)
func GetUsers(c echo.Context) error {
db := c.Get("db").(*bun.DB)
func GetUsers(c fiber.Ctx) error {
db := db.GetDB()
count, err := db.NewSelect().Model((*models.User)(nil)).Count(context.Background())
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "Invalid page number"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "Invalid page number"})
}
// this should be a query param not a URL param
pageStr := c.QueryParam("page")
pageStr := c.Query("page")
if pageStr == "" {
pageStr = "0"
}
@@ -43,7 +43,7 @@ func GetUsers(c echo.Context) error {
limit := 30
if offset > count {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "Invalid page number"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "Invalid page number"})
}
var users []models.User
@@ -54,14 +54,14 @@ func GetUsers(c echo.Context) error {
Order("created_at ASC").
Scan(context.Background())
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "Failed to retrieve users"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "Failed to retrieve users"})
}
if users == nil {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "Invalid page number"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "Invalid page number"})
}
return c.JSON(http.StatusOK, map[string]interface{}{"users": users, "total_users": count})
return c.Status(http.StatusOK).JSON(fiber.Map{"users": users, "total_users": count})
}
type UserEdit struct {
@@ -72,18 +72,18 @@ type UserEdit struct {
Admin bool `json:"is_admin"`
}
func EditUser(c echo.Context) error {
db := c.Get("db").(*bun.DB)
id := c.Param("id")
func EditUser(c fiber.Ctx) error {
db := db.GetDB()
id := c.Params("id")
var userEditData UserEdit
if err := c.Bind(&userEditData); err != nil {
userEditData := new(UserEdit)
if err := c.Bind().JSON(userEditData); err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
if !regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`).MatchString(userEditData.Email) {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "A valid email is required!"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "A valid email is required!"})
}
plan := models.Plan{
@@ -91,12 +91,12 @@ func EditUser(c echo.Context) error {
}
planCount, err := db.NewSelect().Model(&plan).WherePK().Count(context.Background())
if err != nil || planCount == 0 {
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "Invalid plan id!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "Invalid plan id!"})
}
userId, err := uuid.Parse(id)
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
var userData models.User
@@ -104,7 +104,7 @@ func EditUser(c echo.Context) error {
err = db.NewSelect().Model(&userData).WherePK().Relation("Plan").Scan(context.Background())
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
if userEditData.Username != "" {
@@ -118,7 +118,7 @@ func EditUser(c echo.Context) error {
if userEditData.Password != "" {
hash, err := bcrypt.GenerateFromPassword([]byte(userEditData.Password), 12)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
userData.PasswordHash = string(hash)
@@ -134,48 +134,48 @@ func EditUser(c echo.Context) error {
_, err = db.NewUpdate().Model(&userData).WherePK().Exec(context.Background())
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
return c.JSON(http.StatusOK, map[string]string{"message": "Successfully updated user"})
return c.Status(http.StatusOK).JSON(fiber.Map{"message": "Successfully updated user"})
}
func GetPlans(c echo.Context) error {
db := c.Get("db").(*bun.DB)
func GetPlans(c fiber.Ctx) error {
db := db.GetDB()
var plans []models.Plan
err := db.NewSelect().Model(&plans).Scan(context.Background())
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
return c.JSON(http.StatusOK, plans)
return c.Status(http.StatusOK).JSON(plans)
}
func CreateUser(c echo.Context) error {
var signupData models.SignupData
func CreateUser(c fiber.Ctx) error {
signupData := new(models.SignupData)
if err := c.Bind(&signupData); err != nil {
if err := c.Bind().JSON(signupData); err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
if signupData.Username == "" || signupData.Password == "" || signupData.Email == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "A password, username and email are required!"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "A password, username and email are required!"})
}
// if email is not valid
if !regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`).MatchString(signupData.Email) {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "A valid email is required!"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "A valid email is required!"})
}
db := c.Get("db").(*bun.DB)
db := db.GetDB()
hash, err := bcrypt.GenerateFromPassword([]byte(signupData.Password), 12)
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
user := &models.User{
@@ -187,13 +187,13 @@ func CreateUser(c echo.Context) error {
_, err = db.NewInsert().Model(user).Exec(context.Background())
if err != nil {
return c.JSON(http.StatusConflict, map[string]string{"message": "A user with that email or username already exists!"})
return c.Status(http.StatusConflict).JSON(fiber.Map{"message": "A user with that email or username already exists!"})
}
err = db.NewSelect().Model(user).WherePK().Relation("Plan").Scan(context.Background())
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusNotFound, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusNotFound).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
err = os.Mkdir(fmt.Sprintf("%s/%s", os.Getenv("STORAGE_PATH"), user.ID), os.ModePerm)
@@ -202,13 +202,13 @@ func CreateUser(c echo.Context) error {
return err
}
return c.JSON(http.StatusOK, map[string]string{"message": "Successfully created user"})
return c.Status(http.StatusOK).JSON(fiber.Map{"message": "Successfully created user"})
}
// Stolen from Gitea https://github.com/go-gitea/gitea
func SystemStatus(c echo.Context) error {
func SystemStatus(c fiber.Ctx) error {
updateSystemStatus()
return c.JSON(http.StatusOK, map[string]interface{}{
return c.Status(http.StatusOK).JSON(fiber.Map{
"uptime": sysStatus.StartTime,
"num_goroutine": sysStatus.NumGoroutine,
"cur_mem_usage": sysStatus.MemAllocated,

View File

@@ -2,6 +2,7 @@ package routes
import (
"context"
"filething/db"
"filething/models"
"fmt"
"net/http"
@@ -9,31 +10,34 @@ import (
"regexp"
"time"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/uptrace/bun"
"golang.org/x/crypto/bcrypt"
)
func LoginHandler(c echo.Context) error {
var loginData models.LoginData
func LoginHandler(c fiber.Ctx) error {
loginData := new(models.LoginData)
if err := c.Bind(&loginData); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
if err := c.Bind().JSON(loginData); err != nil {
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
// Validate required fields
if loginData.UsernameOrEmail == "" || loginData.Password == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "A password, and username or email are required!"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "A Username/Email and Password are required"})
}
db := c.Get("db").(*bun.DB)
db := db.GetDB()
user := new(models.User)
err := db.NewSelect().Model(user).Where("email = ?", loginData.UsernameOrEmail).Relation("Plan").Scan(context.Background())
if err != nil {
err := db.NewSelect().Model(user).Where("username = ?", loginData.UsernameOrEmail).Relation("Plan").Scan(context.Background())
var err error
// Try both username and email for login attempts
if err = db.NewSelect().Model(user).Where("email = ?", loginData.UsernameOrEmail).Relation("Plan").Scan(context.Background()); err != nil {
err = db.NewSelect().Model(user).Where("username = ?", loginData.UsernameOrEmail).Relation("Plan").Scan(context.Background())
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{"message": "User with that username or email not found!"})
return c.Status(http.StatusNotFound).JSON(fiber.Map{"message": "User not found"})
}
}
@@ -46,49 +50,48 @@ func LoginHandler(c echo.Context) error {
user.Usage = storageUsage
session, err := GenerateSessionToken(db, user.ID)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "Internal server error"})
}
expiration := time.Now().Add(time.Hour * 24 * 365 * 100)
c.SetCookie(&http.Cookie{
c.Cookie(&fiber.Cookie{
Name: "sessionToken",
Value: session.ID.String(),
SameSite: http.SameSiteStrictMode,
SameSite: "Strict",
Expires: expiration,
Path: "/",
})
return c.JSON(http.StatusOK, user)
// Return user data with status code 200 (OK)
return c.JSON(user)
}
var firstUserCreated *bool
func SignupHandler(c echo.Context) error {
var signupData models.SignupData
func SignupHandler(c fiber.Ctx) error {
signupData := new(models.SignupData)
if err := c.Bind(&signupData); err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
if err := c.Bind().JSON(signupData); err != nil {
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
if signupData.Username == "" || signupData.Password == "" || signupData.Email == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "A password, username and email are required!"})
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "A password, username and email are required!"})
}
// if email is not valid
if !regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`).MatchString(signupData.Email) {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "A valid email is required!"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "A valid email is required!"})
}
db := c.Get("db").(*bun.DB)
db := db.GetDB()
hash, err := bcrypt.GenerateFromPassword([]byte(signupData.Password), 12)
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
if firstUserCreated == nil {
@@ -111,7 +114,7 @@ func SignupHandler(c echo.Context) error {
_, err = db.NewInsert().Model(user).Exec(context.Background())
if err != nil {
return c.JSON(http.StatusConflict, map[string]string{"message": "A user with that email or username already exists!"})
return c.Status(http.StatusConflict).JSON(fiber.Map{"message": "A user with that email or username already exists!"})
}
if !*firstUserCreated {
@@ -121,7 +124,7 @@ func SignupHandler(c echo.Context) error {
err = db.NewSelect().Model(user).WherePK().Relation("Plan").Scan(context.Background())
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusNotFound, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusNotFound).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
err = os.Mkdir(fmt.Sprintf("%s/%s", os.Getenv("STORAGE_PATH"), user.ID), os.ModePerm)
@@ -134,20 +137,20 @@ func SignupHandler(c echo.Context) error {
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
expiration := time.Now().Add(time.Hour * 24 * 365 * 100)
c.SetCookie(&http.Cookie{
c.Cookie(&fiber.Cookie{
Name: "sessionToken",
Value: session.ID.String(),
SameSite: http.SameSiteStrictMode,
SameSite: "Strict",
Expires: expiration,
Path: "/",
})
return c.JSON(http.StatusOK, user)
return c.Status(http.StatusOK).JSON(user)
}
func GenerateSessionToken(db *bun.DB, userId uuid.UUID) (*models.Session, error) {
@@ -160,11 +163,11 @@ func GenerateSessionToken(db *bun.DB, userId uuid.UUID) (*models.Session, error)
return session, err
}
func GetUser(c echo.Context) error {
if c.Param("id") == "" {
user := c.Get("user")
func GetUser(c fiber.Ctx) error {
if c.Params("id") == "" {
user := c.Locals("user")
if user == nil {
return c.JSON(http.StatusNotFound, map[string]string{"message": "User not found"})
return c.Status(http.StatusNotFound).JSON(fiber.Map{"message": "User not found"})
}
basePath := fmt.Sprintf("%s/%s/", os.Getenv("STORAGE_PATH"), user.(*models.User).ID)
@@ -175,23 +178,23 @@ func GetUser(c echo.Context) error {
user.(*models.User).Usage = storageUsage
return c.JSON(http.StatusOK, user.(*models.User))
return c.Status(http.StatusOK).JSON(user.(*models.User))
} else {
// get a user from the db using the id parameter, this *should* only be used for admin since /api/admin/users/:id has
// a middleware that checks if the user is an admin, and it should be impossible to pass a param to this endpoint if it isnt that route
db := c.Get("db").(*bun.DB)
db := db.GetDB()
user := new(models.User)
userId, err := uuid.Parse(c.Param("id"))
userId, err := uuid.Parse(c.Params("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
user.ID = userId
err = db.NewSelect().Model(user).WherePK().Relation("Plan").Scan(context.Background())
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{"message": "User not found"})
return c.Status(http.StatusNotFound).JSON(fiber.Map{"message": "User not found"})
}
basePath := fmt.Sprintf("%s/%s/", os.Getenv("STORAGE_PATH"), user.ID)
@@ -202,24 +205,21 @@ func GetUser(c echo.Context) error {
user.Usage = storageUsage
return c.JSON(http.StatusOK, user)
return c.Status(http.StatusOK).JSON(user)
}
}
func LogoutHandler(c echo.Context) error {
db := c.Get("db").(*bun.DB)
func LogoutHandler(c fiber.Ctx) error {
db := db.GetDB()
cookie, err := c.Cookie("sessionToken")
if err != nil {
if err == http.ErrNoCookie {
return echo.NewHTTPError(http.StatusUnauthorized, "Session token missing")
}
return echo.NewHTTPError(http.StatusBadRequest, "Bad request")
cookie := c.Cookies("sessionToken")
if cookie == "" {
return c.Status(http.StatusUnauthorized).JSON(fiber.Map{"message": "Session token missing"})
}
sessionId, err := uuid.Parse(cookie.Value)
sessionId, err := uuid.Parse(cookie)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Bad request")
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "Bad request"})
}
session := &models.Session{
@@ -229,8 +229,8 @@ func LogoutHandler(c echo.Context) error {
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
return c.JSON(http.StatusOK, map[string]string{"message": "Succesfully logged out"})
return c.Status(http.StatusOK).JSON(fiber.Map{"message": "Succesfully logged out"})
}

View File

@@ -12,7 +12,7 @@ import (
"path/filepath"
"strings"
"github.com/labstack/echo/v4"
"github.com/gofiber/fiber/v3"
)
type UploadResponse struct {
@@ -20,10 +20,10 @@ type UploadResponse struct {
File File `json:"file"`
}
func UploadFile(c echo.Context) error {
user := c.Get("user").(*models.User)
func UploadFile(c fiber.Ctx) error {
user := c.Locals("user").(*models.User)
fullPath := strings.Trim(c.Param("*"), "/")
fullPath := strings.Trim(c.Params("*"), "/")
basePath := fmt.Sprintf("%s/%s/%s/", os.Getenv("STORAGE_PATH"), user.ID, fullPath)
currentUsage, err := calculateStorageUsage(fmt.Sprintf("%s/%s", os.Getenv("STORAGE_PATH"), user.ID))
@@ -44,12 +44,12 @@ func UploadFile(c echo.Context) error {
}
}
reader, err := c.Request().MultipartReader()
form, err := c.MultipartForm()
if err != nil {
if err == http.ErrNotMultipart {
if directoryExists {
// Directories exist, but no file was uploaded
return c.JSON(http.StatusBadRequest, map[string]string{"message": "A folder with that name already exists"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "A folder with that name already exists"})
}
// Directories were just created, and no file was provided
entry, err := os.Stat(basePath)
@@ -69,22 +69,18 @@ func UploadFile(c echo.Context) error {
},
}
return c.JSON(http.StatusOK, uploadFile)
return c.Status(http.StatusOK).JSON(uploadFile)
}
fmt.Println(err)
return err
}
part, err := reader.NextPart()
if err != nil {
fmt.Println(err)
return err
}
file := form.File["file"][0]
filepath := filepath.Join(basePath, part.FileName())
filepath := filepath.Join(basePath, file.Filename)
if _, err = os.Stat(filepath); err == nil {
return c.JSON(http.StatusConflict, map[string]string{"message": "File with that name already exists"})
return c.Status(http.StatusConflict).JSON(fiber.Map{"message": "File with that name already exists"})
}
dst, err := os.Create(filepath)
@@ -95,16 +91,22 @@ func UploadFile(c echo.Context) error {
defer dst.Close()
// Read the file manually because otherwise we are limited by the arbitrarily small size of /tmp
buffer := make([]byte, 4096)
buffer := make([]byte, 1*1024*1024)
totalSize := int64(0)
fd, err := file.Open()
if err != nil {
fmt.Println(err)
return err
}
for {
n, readErr := part.Read(buffer)
n, readErr := fd.Read(buffer)
if readErr != nil && readErr == io.ErrUnexpectedEOF {
dst.Close()
os.Remove(filepath)
return c.JSON(http.StatusRequestTimeout, map[string]string{"message": "Upload canceled"})
return c.Status(http.StatusRequestTimeout).JSON(fiber.Map{"message": "Upload canceled"})
}
if readErr != nil && readErr != io.EOF {
@@ -117,7 +119,7 @@ func UploadFile(c echo.Context) error {
if currentUsage+totalSize > user.Plan.MaxStorage {
dst.Close()
os.Remove(filepath)
return c.JSON(http.StatusInsufficientStorage, map[string]string{"message": "Insufficient storage space"})
return c.Status(http.StatusInsufficientStorage).JSON(fiber.Map{"message": "Insufficient storage space"})
}
if _, err := dst.Write(buffer[:n]); err != nil {
@@ -143,7 +145,7 @@ func UploadFile(c echo.Context) error {
},
}
return c.JSON(http.StatusOK, uploadFile)
return c.Status(http.StatusOK).JSON(uploadFile)
}
}
}
@@ -185,10 +187,10 @@ type File struct {
LastModified string `json:"last_modified"`
}
func GetFiles(c echo.Context) error {
user := c.Get("user").(*models.User)
func GetFiles(c fiber.Ctx) error {
user := c.Locals("user").(*models.User)
fullPath := strings.Trim(c.Param("*"), "/")
fullPath := strings.Trim(c.Params("*"), "/")
basePath := fmt.Sprintf("%s/%s/%s/", os.Getenv("STORAGE_PATH"), user.ID, fullPath)
f, err := os.Open(basePath)
@@ -214,22 +216,22 @@ func GetFiles(c echo.Context) error {
})
}
return c.JSON(http.StatusOK, jsonFiles)
return c.Status(http.StatusOK).JSON(jsonFiles)
}
func GetFile(c echo.Context) error {
user := c.Get("user").(*models.User)
func GetFile(c fiber.Ctx) error {
user := c.Locals("user").(*models.User)
fullPath := strings.Trim(c.Param("*"), "/")
fullPath := strings.Trim(c.Params("*"), "/")
fileNamesParam := c.QueryParam("filenames")
fileNamesParam := c.Query("filenames")
var fileNames []string
if fileNamesParam != "" {
fileNames = strings.Split(fileNamesParam, ",")
}
if fullPath == "" && len(fileNames) == 0 {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "A file is required"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "A file is required"})
}
basePath := fmt.Sprintf("%s/%s", os.Getenv("STORAGE_PATH"), user.ID)
@@ -239,12 +241,12 @@ func GetFile(c echo.Context) error {
fileInfo, err := os.Stat(basePath)
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{"message": "No file found!"})
return c.Status(http.StatusNotFound).JSON(fiber.Map{"message": "No file found!"})
}
var buf bytes.Buffer
if fileInfo.IsDir() {
c.Response().Header().Set(echo.HeaderContentType, "application/zip")
c.Type("application/zip")
if len(fileNames) != 0 {
err := zipFiles(&buf, filepath.Join(basePath, fullPath), fileNames)
@@ -253,7 +255,7 @@ func GetFile(c echo.Context) error {
return err
}
_, err = buf.WriteTo(c.Response().Writer)
_, err = buf.WriteTo(c.Response().BodyWriter())
return err
}
@@ -263,10 +265,10 @@ func GetFile(c echo.Context) error {
return err
}
_, err = buf.WriteTo(c.Response().Writer)
_, err = buf.WriteTo(c.Response().BodyWriter())
return err
} else {
return c.File(basePath)
return c.SendFile(basePath)
}
}
@@ -343,21 +345,21 @@ type DeleteRequest struct {
Files []File `json:"files"`
}
func DeleteFiles(c echo.Context) error {
var deleteData DeleteRequest
func DeleteFiles(c fiber.Ctx) error {
deleteData := new(DeleteRequest)
if err := c.Bind(&deleteData); err != nil {
if err := c.Bind().JSON(deleteData); err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
if len(deleteData.Files) == 0 {
return c.JSON(http.StatusBadRequest, map[string]string{"message": "Files are required!"})
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"message": "Files are required!"})
}
user := c.Get("user").(*models.User)
user := c.Locals("user").(*models.User)
fullPath := strings.Trim(c.Param("*"), "/")
fullPath := strings.Trim(c.Params("*"), "/")
basePath := fmt.Sprintf("%s/%s/%s", os.Getenv("STORAGE_PATH"), user.ID, fullPath)
for _, file := range deleteData.Files {
@@ -365,7 +367,7 @@ func DeleteFiles(c echo.Context) error {
err := os.RemoveAll(path)
if err != nil {
fmt.Println(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "An unknown error occoured!"})
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"message": "An unknown error occoured!"})
}
}
@@ -376,5 +378,5 @@ func DeleteFiles(c echo.Context) error {
word = word + "s"
}
return c.JSON(http.StatusOK, map[string]string{"message": fmt.Sprintf("Successfully deleted %d %s", fileLen, word)})
return c.Status(http.StatusOK).JSON(fiber.Map{"message": fmt.Sprintf("Successfully deleted %d %s", fileLen, word)})
}