Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mark #177

Merged
merged 5 commits into from
Oct 2, 2023
Merged

Mark #177

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 59 additions & 6 deletions backend/controllers/files.go
Original file line number Diff line number Diff line change
@@ -1,29 +1,82 @@
package controllers

import (
"backend/configs"
"backend/models"
"backend/responses"
"backend/utils"
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"strings"
)

func UploadFile() gin.HandlerFunc {
func UpdateProfilePicture() gin.HandlerFunc {
return func(c *gin.Context) {
user, err := utils.ExtractTokenUsername(c)

if err != nil {
c.JSON(http.StatusUnauthorized, responses.StandardResponse{
Status: http.StatusUnauthorized,
Message: "Unauthorized. Cannot get information from token. " + err.Error(),
Data: nil,
})
return
}

// strip username from email. ignoring everything after @
user_stripped := user[:strings.Index(user, "@")]
fmt.Println("Username upload: " + user_stripped)

// single file
file, _ := c.FormFile("file")
log.Println(file.Filename)

dst := "./uploads" + file.Filename
// get the file type from filename
fileType := file.Filename[strings.LastIndex(file.Filename, ".")+1:]

newFileName := user_stripped + "." + fileType

dst := "./uploads/" + newFileName
fmt.Println("File: " + dst)

// Actualizar en base de datos
userType, err := utils.ExtractTokenUserType(c)

if err != nil {
c.JSON(http.StatusUnauthorized, responses.StandardResponse{
Status: http.StatusUnauthorized,
Message: "Unauthorized. Cannot get information from token. " + err.Error(),
Data: nil,
})
return
}

if userType == "student" {
err = configs.DB.Model(&models.Estudiante{}).Where("correo = ?", user).Updates(models.Estudiante{Foto: newFileName}).Error
} else if userType == "company" {
err = configs.DB.Model(&models.Empresa{}).Where("correo = ?", user).Updates(models.Empresa{Foto: newFileName}).Error
}

// Upload the file to specific dst.
err := c.SaveUploadedFile(file, dst)
err = c.SaveUploadedFile(file, dst)
if err != nil {
return
}

c.JSON(http.StatusOK, responses.StandardResponse{
Status: http.StatusOK,
Message: "File uploaded successfully",
Data: nil,
Data: map[string]interface{}{
"filename": newFileName,
},
})
}
}

func GetFile() gin.HandlerFunc {
return func(c *gin.Context) {
filename := c.Param("filename")
filePath := "./uploads/" + filename
c.File(filePath) // Esto sirve el archivo al cliente
}
}
4 changes: 3 additions & 1 deletion backend/routes/routes_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ func Routes(router *gin.Engine) {
public.POST("/companies", controllers.NewCompany)
public.GET("/postulations/previews", controllers.GetOfferPreviews)

router.POST("/upload", controllers.UploadFile())
// Rutas de archivos
public.GET("/uploads/:filename", controllers.GetFile())

// Rutas protegidas
// Mensajes
Expand All @@ -33,6 +34,7 @@ func Routes(router *gin.Engine) {

users.GET("/", controllers.CurrentUser)
users.POST("/details", controllers.GetUserDetails)
users.PUT("/upload", controllers.UpdateProfilePicture())

// Estudiantes
students := router.Group("api/students")
Expand Down
32 changes: 32 additions & 0 deletions backend/tests/load/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import requests
import concurrent.futures

# URL y JSON de solicitud
url = "https://whole-letisha-markalbrand56.koyeb.app/api/login"
payload = {
"usuario": "prueba@prueba",
"contra": "prueba"
}


# Función para enviar una solicitud HTTP
def send_request(url, payload):
try:
response = requests.post(url, json=payload)
if response.status_code == 200:
print("Solicitud exitosa")
else:
print(f"Fallo en la solicitud: {response.status_code}")
except Exception as e:
print(f"Error: {str(e)}")


# Número de hilos concurrentes
num_threads = 200 # Puedes ajustar este valor según tus necesidades

# Crear un ThreadPoolExecutor para enviar solicitudes concurrentes
with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
futures = [executor.submit(send_request, url, payload) for _ in range(num_threads)]

# Esperar a que todas las solicitudes se completen
concurrent.futures.wait(futures)
Loading