jlelse
/
hugo-micropub
Archived
1
Fork 0
This repository has been archived on 2020-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
hugo-micropub/mediastorage.go

48 lines
1.1 KiB
Go

package main
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"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(http.MethodPut, 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
}
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
}