Fix a couple deprecated calls and handle errors

This commit is contained in:
max 2023-05-04 08:40:35 -05:00
parent d0da1a9114
commit baef0cbe78

View File

@ -4,8 +4,9 @@ import (
"GoWeb/app" "GoWeb/app"
"GoWeb/models" "GoWeb/models"
"GoWeb/security" "GoWeb/security"
"io/ioutil" "io"
"log" "log"
"mime/multipart"
"net/http" "net/http"
"os" "os"
"time" "time"
@ -73,12 +74,14 @@ func (postController *PostController) Register(w http.ResponseWriter, r *http.Re
} }
func (postController *PostController) FileUpload(w http.ResponseWriter, r *http.Request) { func (postController *PostController) FileUpload(w http.ResponseWriter, r *http.Request) {
max := postController.App.Config.Upload.MaxSize max := postController.App.Config.Upload.MaxSize
r.ParseMultipartForm(max) err := r.ParseMultipartForm(max)
if err != nil {
return
}
// FormFile returns the first file for the given key `file` // FormFile returns the first file for the given key `file`
// it also returns the FileHeader so we can get the Filename, // it also returns the FileHeader, so we can get the Filename,
// the Header and the size of the file // the Header and the size of the file
file, handler, err := r.FormFile("file") file, handler, err := r.FormFile("file")
if err != nil { if err != nil {
@ -86,7 +89,12 @@ func (postController *PostController) FileUpload(w http.ResponseWriter, r *http.
log.Println(err) log.Println(err)
return return
} }
defer file.Close() defer func(file multipart.File) {
err := file.Close()
if err != nil {
log.Println(err)
}
}(file)
if handler.Size > max { if handler.Size > max {
log.Println("User tried uploading a file which is too large.") log.Println("User tried uploading a file which is too large.")
@ -100,17 +108,24 @@ func (postController *PostController) FileUpload(w http.ResponseWriter, r *http.
log.Println(err) log.Println(err)
http.Redirect(w, r, "/", http.StatusNotAcceptable) http.Redirect(w, r, "/", http.StatusNotAcceptable)
} }
defer tempFile.Close() defer func(tempFile *os.File) {
err := tempFile.Close()
// read all of the contents of our uploaded file into a if err != nil {
// byte array log.Println(err)
fileBytes, err := ioutil.ReadAll(file) }
}(tempFile)
// read all the contents of our uploaded file into a
// byte array
fileBytes, err := io.ReadAll(file)
if err != nil {
log.Println(err)
}
_, err = tempFile.Write(fileBytes)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
// write this byte array to our temporary file
tempFile.Write(fileBytes)
// return that we have successfully uploaded our file!
http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/", http.StatusFound)
} }