Skip to content

Instantly share code, notes, and snippets.

@mbonell
Last active April 26, 2017 04:24
Show Gist options
  • Save mbonell/badacad084668b56c5eed94d4e241931 to your computer and use it in GitHub Desktop.
Save mbonell/badacad084668b56c5eed94d4e241931 to your computer and use it in GitHub Desktop.
First steps using Gophercloud to interact with OpenStack Swift API
package main
import (
"bufio"
"log"
"os"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/gophercloud/openstack/objectstorage/v1/containers"
"github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects"
)
func main() {
// Get OpenStack auth values from environment
authOpts, err := openstack.AuthOptionsFromEnv()
if err != nil {
log.Println(err)
return
}
// Autenticate into OpenStack
provider, err := openstack.AuthenticatedClient(authOpts)
if err != nil {
log.Println(err)
return
}
// Create the service client for interact with swift
var regionName = os.Getenv("OS_REGION_NAME")
objectClient, err := openstack.NewObjectStorageV1(provider, gophercloud.EndpointOpts{
Region: regionName,
})
if err != nil {
log.Println(err)
return
}
// Create a storage container
log.Println("Creating a container...")
containerName := "gophercloud-container"
containers.Create(objectClient, containerName, nil)
// Upload an image to the cloud
filePath := "pics/logo.png"
objectName := "gophercloud amazing logo"
f, _ := os.Open(filePath)
defer f.Close()
reader := bufio.NewReader(f)
options := objects.CreateOpts{
Content: reader,
}
log.Println("Uploading a image using the object storage service...")
objects.Create(objectClient, containerName, objectName, options)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment