59 lines
1.8 KiB
Go
59 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func HandleMedia(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != "POST" {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
_, _ = w.Write([]byte("The HTTP method is not allowed, make a POST request"))
|
|
return
|
|
}
|
|
if contentType := r.Header.Get("content-type"); !strings.Contains(contentType, "multipart/form-data") {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
_, _ = w.Write([]byte("Wrong Content-Type"))
|
|
return
|
|
}
|
|
err := r.ParseMultipartForm(0)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("Failed to parse Multipart"))
|
|
return
|
|
}
|
|
authCode := r.Header.Get("authorization")
|
|
if formAuth := r.FormValue("authorization"); len(authCode) == 0 && len(formAuth) > 0 {
|
|
authCode = formAuth
|
|
}
|
|
if CheckAuthorization(authCode) {
|
|
file, header, err := r.FormFile("file")
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("Failed to get file"))
|
|
return
|
|
}
|
|
fileName := generateRandomString(time.Now(), 15)
|
|
mimeType := header.Header.Get("content-type")
|
|
originalName := header.Filename
|
|
if strings.Contains(mimeType, "jpeg") || strings.Contains(originalName, ".jpeg") || strings.Contains(originalName, ".jpg") {
|
|
fileName += ".jpg"
|
|
} else if strings.Contains(mimeType, "png") || strings.Contains(originalName, ".png") {
|
|
fileName += ".png"
|
|
}
|
|
location, err := SelectedMediaStorage.Upload(fileName, file)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("Failed to upload file"))
|
|
return
|
|
}
|
|
w.Header().Add("Location", location)
|
|
w.WriteHeader(http.StatusCreated)
|
|
} else {
|
|
w.WriteHeader(http.StatusForbidden)
|
|
_, _ = w.Write([]byte("Forbidden, there was a problem with the provided access token"))
|
|
return
|
|
}
|
|
}
|