Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
// lol kekekekekekkekekek
"github.com/valyala/fasthttp"
// Make an upload signature
"time"
"strconv"
"crypto/sha1"
"encoding/hex"
"path/filepath"
"net/url"
"encoding/base64"
"encoding/json"
// Read a file from argv
"os"
"io/ioutil"
"fmt"
)
var CloudinaryKey string
var CloudinarySecret string
var CloudinaryName string
var Client = &fasthttp.Client{}
// i wanted a fast way to decode the JSON Cloudinary returns lol
type CloudinaryUploadURLThing struct {
URL string `json:"secure_url"`
}
func main() {
if len(os.Args) < 5 {
fmt.Println("usage: " + os.Args[0] + " [image filename] [cloudinary key] [cloudinary secret] [cloudinary name]")
os.Exit(0)
}
fileData, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("error while reading image file", err)
os.Exit(1)
}
fileExt := filepath.Ext(os.Args[1])[1:]
CloudinaryKey = os.Args[2]
CloudinarySecret = os.Args[3]
CloudinaryName = os.Args[4]
// Generate an upload "signature" for Cloudinary right now, since it needs that
// "timestamp="+ a unix timestamp, and a cloudinary secret appended to it
// Then, SHA-1 encode it and also encode that to hex
uploadSignature := "timestamp=" + strconv.Itoa(int(time.Now().Unix())) + CloudinarySecret
hash := sha1.New()
hash.Write([]byte(uploadSignature))
uploadSignatureHash := hash.Sum(nil)
uploadSignatureFinal := make([]byte, hex.EncodedLen(len(uploadSignatureHash)))
hex.Encode(uploadSignatureFinal, uploadSignatureHash)
// Hex signature is now in uploadSignatureFinal as a []byte
// Make a payload now
reqBody := "api_key=" + CloudinaryKey + "&timestamp=" + strconv.Itoa(int(time.Now().Unix())) + "&signature=" + string(uploadSignatureFinal) + "&file=" + url.QueryEscape("data:image/" + fileExt + ";base64," + base64.StdEncoding.EncodeToString(fileData))
// lol that was total spaghetti but it works
// Upload to Cloudinary now
// if you're making this work with multiple uploads, DO NOT CREATE A REQUEST AND RESPONSE every time!!!!!
// Acquire them once and use them over and over again, same with the Client. That's how it's meant to be used.
req := fasthttp.AcquireRequest()
req.SetRequestURI("https://api.cloudinary.com/v1_1/" + CloudinaryName + "/image/upload")
req.Header.SetMethod("POST")
req.Header.SetContentType("application/x-www-form-urlencoded")
req.SetBody([]byte(reqBody))
resp := fasthttp.AcquireResponse()
err = Client.Do(req, resp)
if err != nil {
fmt.Println("error while uploading to cloudinary", err)
os.Exit(1)
}
if resp.StatusCode() > 300 {
fmt.Println("http response code " + strconv.Itoa(resp.StatusCode()) + ", " + string(resp.Body()))
os.Exit(1)
}
// now unmarshal the json and print it out
var imageURL CloudinaryUploadURLThing
json.Unmarshal(resp.Body(), &imageURL)
fmt.Println(imageURL.URL)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.