s3manager-web/create-object.go

83 lines
2.1 KiB
Go
Raw Normal View History

2017-04-03 14:08:01 +02:00
package main
2017-03-30 22:48:27 +02:00
import (
"encoding/json"
"fmt"
2017-04-19 14:18:58 +02:00
"log"
2017-03-30 22:48:27 +02:00
"net/http"
"github.com/gorilla/mux"
minio "github.com/minio/minio-go"
)
// CopyObjectInfo is the information about an object to copy
type CopyObjectInfo struct {
BucketName string `json:"bucketName"`
ObjectName string `json:"objectName"`
SourceBucketName string `json:"sourceBucketName"`
SourceObjectName string `json:"sourceObjectName"`
}
2017-04-14 19:52:16 +02:00
// CreateObjectFromJSONHandler allows to copy an existing object
func CreateObjectFromJSONHandler(s3 S3Client) http.Handler {
2017-03-30 22:48:27 +02:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2017-04-14 19:52:16 +02:00
var copy CopyObjectInfo
2017-03-30 22:48:27 +02:00
2017-04-14 19:52:16 +02:00
err := json.NewDecoder(r.Body).Decode(&copy)
if err != nil {
handleHTTPError(w, http.StatusInternalServerError, err)
return
}
2017-03-30 22:48:27 +02:00
2017-04-14 19:52:16 +02:00
copyConds := minio.NewCopyConditions()
objectSource := fmt.Sprintf("/%s/%s", copy.SourceBucketName, copy.SourceObjectName)
err = s3.CopyObject(copy.BucketName, copy.ObjectName, objectSource, copyConds)
if err != nil {
handleHTTPError(w, http.StatusInternalServerError, err)
return
}
2017-03-30 22:48:27 +02:00
2017-04-14 19:52:16 +02:00
w.Header().Set(headerContentType, contentTypeJSON)
w.WriteHeader(http.StatusCreated)
2017-03-30 22:48:27 +02:00
2017-04-14 19:52:16 +02:00
err = json.NewEncoder(w).Encode(copy)
if err != nil {
handleHTTPError(w, http.StatusInternalServerError, err)
return
}
})
}
2017-03-30 22:48:27 +02:00
2017-04-14 19:52:16 +02:00
// CreateObjectFromFormHandler allows to upload a new object
func CreateObjectFromFormHandler(s3 S3Client) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
2017-03-30 22:48:27 +02:00
2017-04-14 19:52:16 +02:00
err := r.ParseMultipartForm(32 << 20)
if err != nil {
handleHTTPError(w, http.StatusUnprocessableEntity, err)
return
}
2017-03-30 22:48:27 +02:00
2017-04-14 19:52:16 +02:00
file, handler, err := r.FormFile("file")
if err != nil {
handleHTTPError(w, http.StatusInternalServerError, err)
return
}
2017-04-19 14:18:58 +02:00
defer func() {
err = file.Close()
if err != nil {
log.Fatalln(err)
}
}()
2017-03-30 22:48:27 +02:00
2017-04-14 19:52:16 +02:00
_, err = s3.PutObject(vars["bucketName"], handler.Filename, file, contentTypeOctetStream)
if err != nil {
handleHTTPError(w, http.StatusInternalServerError, err)
return
2017-03-30 22:48:27 +02:00
}
2017-04-14 19:52:16 +02:00
w.WriteHeader(http.StatusCreated)
2017-03-30 22:48:27 +02:00
})
}