-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathattachment.go
103 lines (84 loc) · 2.45 KB
/
attachment.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package sofa
import (
"encoding/json"
"io"
)
// Attachment represents files or other data which is attached to documents in the
// Database.
type Attachment struct {
ContentType string `json:"content_type,omitempty"`
Data string `json:"data,omitempty"`
Digest string `json:"digest,omitempty"`
EncodedLength float64 `json:"encoded_length,omitempty"`
Encoding string `json:"encoding,omitempty"`
Length int64 `json:"length,omitempty"`
RevPos float64 `json:"revpos,omitempty"`
Stub bool `json:"stub,omitempty"`
Follows bool `json:"follows,omitempty"`
}
type attachmentPutResponse struct {
ID string `json:"id"`
Rev string `json:"rev"`
OK bool `json:"ok"`
}
// GetAttachment gets the current attachment and returns
func (db *Database) GetAttachment(docid, name, rev string) ([]byte, error) {
path := urlConcat(db.DocumentPath(docid), name)
opts := NewURLOptions()
if rev != "" {
if err := opts.Set("rev", rev); err != nil {
return nil, err
}
}
resp, err := db.con.Get(path, opts)
if err != nil {
return nil, err
}
return io.ReadAll(resp.Body)
}
// PutAttachment replaces the content of the attachment with new content read from an
// io.Reader or creates it if it does not exist. If the provided rev is not the most
// recent then an error will be returned from CouchDB.
func (db *Database) PutAttachment(docid, name string, doc io.Reader, rev string) (string, error) {
path := urlConcat(db.DocumentPath(docid), name)
opts := NewURLOptions()
if rev != "" {
if err := opts.Set("rev", rev); err != nil {
return "", err
}
}
resp, err := db.con.Put(path, opts, doc)
if err != nil {
return "", err
}
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
ar := attachmentPutResponse{}
if err := json.Unmarshal(respBytes, &ar); err != nil {
return "", err
}
return ar.Rev, nil
}
// DeleteAttachment removes an attachment from a document in CouchDB.
func (db *Database) DeleteAttachment(docid, name, rev string) (string, error) {
path := urlConcat(db.DocumentPath(docid), name)
opts := NewURLOptions()
if err := opts.Set("rev", rev); err != nil {
return "", err
}
resp, err := db.con.Delete(path, opts)
if err != nil {
return "", err
}
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
ar := attachmentPutResponse{}
if err := json.Unmarshal(respBytes, &ar); err != nil {
return "", err
}
return ar.Rev, nil
}