Image Upload Code Sample - Golang
Image Upload Code Sample - Golang
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
)
func main() {
domainPrefix := os.Getenv("VEND_DOMAIN_PREFIX")
productID := os.Getenv("VEND_PRODUCT_ID") // this wouldn't usually come from an evironment variable
filePath := os.Getenv("VEND_IMAGE_FILEPATH") // ditto
token := os.Getenv("VEND_TOKEN")
var body bytes.Buffer
writer := multipart.NewWriter(&body)
file, err := os.Open(filePath)
if err != nil {
log.Fatal(err)
}
defer file.Close()
part, err := writer.CreateFormFile("image", filePath)
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(part, file)
if err != nil {
log.Fatal(err)
}
err = writer.Close()
if err != nil {
log.Fatal(err)
}
url := fmt.Sprintf("https://%s.retail.lightspeed.app/api/2.0/products/%s/actions/image_upload", domainPrefix, productID)
req, err := http.NewRequest("POST", url, &body)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(resBody))
}
Updated 9 months ago