2020-01-01 12:44:44 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2020-01-19 09:55:18 +00:00
|
|
|
"crypto/sha256"
|
2020-01-01 12:44:44 +00:00
|
|
|
"errors"
|
2020-01-19 09:55:18 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2020-01-01 12:44:44 +00:00
|
|
|
"mime/multipart"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
)
|
|
|
|
|
|
|
|
type MediaStorage interface {
|
|
|
|
Upload(fileName string, file multipart.File) (location string, err error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// BunnyCDN
|
|
|
|
type BunnyCdnStorage struct {
|
|
|
|
// Access Key
|
|
|
|
key string
|
|
|
|
// Storage zone name
|
|
|
|
storageZoneName string
|
|
|
|
// Base location
|
|
|
|
baseLocation string
|
|
|
|
}
|
|
|
|
|
|
|
|
var bunnyCdnStorageUrl = "https://storage.bunnycdn.com"
|
|
|
|
|
2020-04-20 18:59:11 +00:00
|
|
|
func (b *BunnyCdnStorage) Upload(fileName string, file multipart.File) (location string, err error) {
|
2020-04-20 21:04:01 +00:00
|
|
|
client := http.DefaultClient
|
2020-05-14 20:32:00 +00:00
|
|
|
req, _ := http.NewRequest(http.MethodPut, bunnyCdnStorageUrl+"/"+url.PathEscape(b.storageZoneName)+"/"+url.PathEscape(fileName), file)
|
2020-01-01 12:44:44 +00:00
|
|
|
req.Header.Add("AccessKey", b.key)
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil || resp.StatusCode != 201 {
|
|
|
|
return "", errors.New("failed to upload file to BunnyCDN")
|
|
|
|
}
|
|
|
|
return b.baseLocation + fileName, nil
|
|
|
|
}
|
2020-01-19 09:55:18 +00:00
|
|
|
|
|
|
|
func getSHA256(file multipart.File) (filename string, err error) {
|
|
|
|
h := sha256.New()
|
|
|
|
if _, e := io.Copy(h, file); e != nil {
|
|
|
|
err = errors.New("failed to calculate hash of file")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%x", h.Sum(nil)), nil
|
|
|
|
}
|