hugo-micropub/mediastorage.go

48 lines
1.1 KiB
Go
Raw Normal View History

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"
func (b BunnyCdnStorage) Upload(fileName string, file multipart.File) (location string, err error) {
client := &http.Client{}
req, _ := http.NewRequest("PUT", bunnyCdnStorageUrl+"/"+url.PathEscape(b.storageZoneName)+"/"+url.PathEscape("/"+fileName), file)
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
}