Skip to content

Instantly share code, notes, and snippets.

@BackgroundCut
Created November 14, 2023 04:17
Show Gist options
  • Save BackgroundCut/1443972fded56db1a8a3242ecdc2f77b to your computer and use it in GitHub Desktop.
Save BackgroundCut/1443972fded56db1a8a3242ecdc2f77b to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"time"
)
const (
apiEndpoint = "https://api.backgroundcut.co/v2/cut/"
apiKey = "YOUR-API-KEY"
imagePath = "/path/to/image.jpg"
localOutputFile = "/path/to/output.webp"
timeoutDuration = 20 * time.Second
// Request parameters as constants
requestQuality = "medium"
requestReturnFormat = "webp"
requestMaxResolution = "12000000"
)
func main() {
// Create a new HTTP client with a timeout
client := &http.Client{
Timeout: timeoutDuration,
}
// Prepare the file to be uploaded
file, err := os.Open(imagePath)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
// Prepare a form that you will submit to the server
var b bytes.Buffer
w := multipart.NewWriter(&b)
fw, err := w.CreateFormFile("image_file", imagePath)
if err != nil {
fmt.Println("Error creating form file:", err)
return
}
// Copy the file to the form
_, err = io.Copy(fw, file)
if err != nil {
fmt.Println("Error copying file to form:", err)
return
}
// Add other fields using constants
w.WriteField("quality", requestQuality)
w.WriteField("return_format", requestReturnFormat)
w.WriteField("max_resolution", requestMaxResolution)
// Close the writer
w.Close()
// Create a request
req, err := http.NewRequest("POST", apiEndpoint, &b)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set headers and authorization
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Set("Authorization", apiKey)
// Send the request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Check the response status
if resp.StatusCode == http.StatusOK {
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
// Write the response to a file
err = ioutil.WriteFile(localOutputFile, body, 0644)
if err != nil {
fmt.Println("Error writing to file:", err)
return
}
} else {
// Handle error response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Error: Status Code %d, Body: %s\n", resp.StatusCode, string(body))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment