You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

127 lines
2.8 KiB

package Api
import (
"encoding/json"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Util"
"github.com/gofrs/uuid"
)
func createPostImage(w http.ResponseWriter, r *http.Request) {
var (
postData Models.Post
postID string
postUUID uuid.UUID
postImage Models.PostImage
formData *multipart.Form
fileHeaders []*multipart.FileHeader
fileHeader *multipart.FileHeader
file multipart.File
fileBytes []byte
fileObject Util.FileObject
returnJson []byte
err error
)
postID, err = Util.GetPostId(r)
if err != nil {
log.Printf("Error encountered getting id\n")
Util.JsonReturn(w, 500, "An error occured")
return
}
postUUID = uuid.FromStringOrNil(postID)
err = r.ParseMultipartForm(20 << 20)
if err != nil {
log.Printf("Error encountered parsing multipart form: %s\n", err.Error())
Util.JsonReturn(w, 500, "An error occured")
return
}
formData = r.MultipartForm
fileHeaders = formData.File["files"]
for _, fileHeader = range fileHeaders {
file, err = fileHeader.Open()
if err != nil {
log.Printf("Error encountered while post image upload: %s\n", err.Error())
Util.JsonReturn(w, 500, "An error occured")
return
}
defer file.Close()
fileBytes, err = ioutil.ReadAll(file)
if err != nil {
log.Printf("Error encountered while post image upload: %s\n", err.Error())
Util.JsonReturn(w, 500, "An error occured")
return
}
fileObject, err = Util.WriteFile(fileBytes, "image")
if err != nil {
log.Printf("Error encountered while post image upload: %s\n", err.Error())
Util.JsonReturn(w, 415, "Invalid filetype")
return
}
postImage = Models.PostImage{
PostID: postUUID,
Filepath: fileObject.Filepath,
Mimetype: fileObject.Mimetype,
Size: fileObject.Size,
}
err = Database.CreatePostImage(&postImage)
if err != nil {
log.Printf("Error encountered while creating post_image record: %s\n", err.Error())
Util.JsonReturn(w, 500, "An error occured")
return
}
}
postData, err = Util.GetPostById(w, r)
if err != nil {
return
}
returnJson, err = json.MarshalIndent(postData, "", " ")
if err != nil {
Util.JsonReturn(w, 500, "An error occured")
return
}
// Return updated json
w.WriteHeader(http.StatusOK)
w.Write(returnJson)
}
func deletePostImage(w http.ResponseWriter, r *http.Request) {
var (
postImageData Models.PostImage
err error
)
postImageData, err = Util.GetPostImageById(w, r)
if err != nil {
return
}
err = Database.DeletePostImage(&postImageData)
if err != nil {
log.Printf("An error occured: %s\n", err.Error())
Util.JsonReturn(w, 500, "An error occured")
return
}
// Return updated json
w.WriteHeader(http.StatusOK)
}