s3manager-web/get-object.go

38 lines
914 B
Go
Raw Normal View History

2017-04-03 14:08:01 +02:00
package main
2017-03-30 22:48:27 +02:00
import (
"fmt"
"io"
"net/http"
"github.com/gorilla/mux"
)
2017-04-03 14:08:01 +02:00
// GetObjectHandler downloads an object to the client
func GetObjectHandler(s3 S3Client) http.Handler {
2017-03-30 22:48:27 +02:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
2017-04-21 15:42:00 +02:00
bucketName := vars["bucketName"]
2017-03-30 22:48:27 +02:00
objectName := vars["objectName"]
2017-04-21 15:42:00 +02:00
object, err := s3.GetObject(bucketName, objectName)
2017-03-30 22:48:27 +02:00
if err != nil {
2017-04-09 16:28:57 +02:00
handleHTTPError(w, http.StatusInternalServerError, err)
2017-03-30 22:48:27 +02:00
return
}
2017-04-07 10:07:23 +02:00
w.Header().Set(headerContentDisposition, fmt.Sprintf("attachment; filename=\"%s\"", objectName))
w.Header().Set(headerContentType, contentTypeOctetStream)
2017-03-30 22:48:27 +02:00
_, err = io.Copy(w, object)
if err != nil {
2017-04-03 23:52:41 +02:00
code := http.StatusInternalServerError
2017-04-09 16:28:57 +02:00
if err.Error() == ErrBucketDoesNotExist || err.Error() == ErrKeyDoesNotExist {
2017-04-03 23:52:41 +02:00
code = http.StatusNotFound
}
2017-04-09 16:28:57 +02:00
handleHTTPError(w, code, err)
2017-03-30 22:48:27 +02:00
return
}
})
}