| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package fileblob |
| 16 |
|
| 17 |
import ( |
| 18 |
"encoding/json" |
| 19 |
"fmt" |
| 20 |
"os" |
| 21 |
) |
| 22 |
|
| 23 |
const attrsExt = ".attrs" |
| 24 |
|
| 25 |
var errAttrsExt = fmt.Errorf("file extension %q is reserved", attrsExt) |
| 26 |
|
| 27 |
// xattrs stores extended attributes for an object. The format is like |
| 28 |
// filesystem extended attributes, see |
| 29 |
// https://www.freedesktop.org/wiki/CommonExtendedAttributes. |
| 30 |
type xattrs struct { |
| 31 |
CacheControl string `json:"user.cache_control"` |
| 32 |
ContentDisposition string `json:"user.content_disposition"` |
| 33 |
ContentEncoding string `json:"user.content_encoding"` |
| 34 |
ContentLanguage string `json:"user.content_language"` |
| 35 |
ContentType string `json:"user.content_type"` |
| 36 |
Metadata map[string]string `json:"user.metadata"` |
| 37 |
MD5 []byte `json:"md5"` |
| 38 |
} |
| 39 |
|
| 40 |
// setAttrs creates a "path.attrs" file along with blob to store the attributes, |
| 41 |
// it uses JSON format. |
| 42 |
func setAttrs(path string, xa xattrs) error { |
| 43 |
f, err := os.Create(path + attrsExt) |
| 44 |
if err != nil { |
| 45 |
return err |
| 46 |
} |
| 47 |
if err := json.NewEncoder(f).Encode(xa); err != nil { |
| 48 |
f.Close() |
| 49 |
os.Remove(f.Name()) |
| 50 |
return err |
| 51 |
} |
| 52 |
return f.Close() |
| 53 |
} |
| 54 |
|
| 55 |
// getAttrs looks at the "path.attrs" file to retrieve the attributes and |
| 56 |
// decodes them into a xattrs struct. It doesn't return error when there is no |
| 57 |
// such .attrs file. |
| 58 |
func getAttrs(path string) (xattrs, error) { |
| 59 |
f, err := os.Open(path + attrsExt) |
| 60 |
if err != nil { |
| 61 |
if os.IsNotExist(err) { |
| 62 |
// Handle gracefully for non-existent .attr files. |
| 63 |
return xattrs{ |
| 64 |
ContentType: "application/octet-stream", |
| 65 |
}, nil |
| 66 |
} |
| 67 |
return xattrs{}, err |
| 68 |
} |
| 69 |
xa := new(xattrs) |
| 70 |
if err := json.NewDecoder(f).Decode(xa); err != nil { |
| 71 |
f.Close() |
| 72 |
return xattrs{}, err |
| 73 |
} |
| 74 |
return *xa, f.Close() |
| 75 |
} |