summaryrefslogtreecommitdiff
path: root/imagestore/gcsstore.go
diff options
context:
space:
mode:
authorhorus_arch2015-04-19 22:09:52 +0200
committerhorus_arch2015-04-19 22:09:52 +0200
commit01e9a34952bd6ddd383680b0ca2312e476ad07a6 (patch)
tree00902575e5c271cc5d35ea65aa8795b8caeb97bc /imagestore/gcsstore.go
downloadmandible-01e9a34952bd6ddd383680b0ca2312e476ad07a6.tar.gz
Initial commit.
Diffstat (limited to 'imagestore/gcsstore.go')
-rw-r--r--imagestore/gcsstore.go62
1 files changed, 62 insertions, 0 deletions
diff --git a/imagestore/gcsstore.go b/imagestore/gcsstore.go
new file mode 100644
index 0000000..798d4eb
--- /dev/null
+++ b/imagestore/gcsstore.go
@@ -0,0 +1,62 @@
+package imagestore
+
+import (
+ "io/ioutil"
+ "log"
+
+ "golang.org/x/net/context"
+ "google.golang.org/cloud/storage"
+)
+
+type GCSImageStore struct {
+ ctx context.Context
+ bucketName string
+ storeRoot string
+ namePathMapper *NamePathMapper
+}
+
+func NewGCSImageStore(ctx context.Context, bucket string, root string, mapper *NamePathMapper) *GCSImageStore {
+ return &GCSImageStore{
+ ctx: ctx,
+ bucketName: bucket,
+ storeRoot: root,
+ namePathMapper: mapper,
+ }
+}
+
+func (this *GCSImageStore) Exists(obj *StoreObject) (bool, error) {
+ _, err := storage.StatObject(this.ctx, this.bucketName, this.toPath(obj))
+ if err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
+func (this *GCSImageStore) Save(src string, obj *StoreObject) (*StoreObject, error) {
+ data, err := ioutil.ReadFile(src)
+ if err != nil {
+ log.Printf("error on read file: %s", err)
+ return nil, err
+ }
+
+ wc := storage.NewWriter(this.ctx, this.bucketName, this.toPath(obj))
+ wc.ContentType = obj.MimeType
+ if _, err := wc.Write(data); err != nil {
+ log.Printf("error on write data: %s", err)
+ return nil, err
+ }
+ if err := wc.Close(); err != nil {
+ log.Printf("error on close writer: %s", err)
+ return nil, err
+ }
+
+ obj.Url = "https://storage.googleapis.com/" + this.bucketName + "/" + this.toPath(obj)
+ return obj, nil
+}
+
+func (this *GCSImageStore) toPath(obj *StoreObject) string {
+ if this.storeRoot != "" {
+ return this.storeRoot + "/" + this.namePathMapper.mapToPath(obj)
+ }
+ return this.namePathMapper.mapToPath(obj)
+}