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.DefaultClient 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 }