forked from rhinoman/couchdb-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcouchdb.go
856 lines (788 loc) · 21.8 KB
/
couchdb.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//Package couchdb provides a simple REST client for CouchDB
package couchdb
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
type Connection struct{ *connection }
type Database struct {
dbName string
connection *Connection
auth Auth
}
//Creates a regular http connection.
//Timeout sets the timeout for the http Client
func NewConnection(address string, port int,
timeout time.Duration) (*Connection, error) {
url := "http://" + address + ":" + strconv.Itoa(port)
return createConnection(url, timeout)
}
//Creates an https connection.
//Timeout sets the timeout for the http Client
func NewSSLConnection(address string, port int,
timeout time.Duration) (*Connection, error) {
url := "https://" + address + ":" + strconv.Itoa(port)
return createConnection(url, timeout)
}
func createConnection(rawUrl string, timeout time.Duration) (*Connection, error) {
//check that the url is valid
theUrl, err := url.Parse(rawUrl)
if err != nil {
return nil, err
}
return &Connection{
&connection{
url: theUrl.String(),
client: &http.Client{Timeout: timeout},
},
}, nil
}
//Use to check if database server is alive.
func (conn *Connection) Ping() error {
resp, err := conn.request("HEAD", "/", nil, nil, nil)
if err == nil {
resp.Body.Close()
}
return err
}
//DATABASES.
//Return a list of all databases on the server
func (conn *Connection) GetDBList() (dbList []string, err error) {
resp, err := conn.request("GET", "/_all_dbs", nil, nil, nil)
if err != nil {
return dbList, err
}
err = parseBody(resp, &dbList)
return dbList, err
}
//Create a new Database.
func (conn *Connection) CreateDB(name string, auth Auth) error {
url, err := buildUrl(name)
if err != nil {
return err
}
resp, err := conn.request("PUT", url, nil, nil, auth)
if err == nil {
resp.Body.Close()
}
return err
}
//Delete a Database.
func (conn *Connection) DeleteDB(name string, auth Auth) error {
url, err := buildUrl(name)
if err != nil {
return err
}
resp, err := conn.request("DELETE", url, nil, nil, auth)
if err == nil {
resp.Body.Close()
}
return err
}
//Set a CouchDB configuration option
func (conn *Connection) SetConfig(section string,
option string, value string, auth Auth) error {
url, err := buildUrl("_node/_local/_config", section, option)
if err != nil {
return err
}
body := strings.NewReader("\"" + value + "\"")
resp, err := conn.request("PUT", url, body, nil, auth)
if err == nil {
resp.Body.Close()
}
return err
}
//Gets a CouchDB configuration option
func (conn *Connection) GetConfigOption(section string,
option string, auth Auth) (string, error) {
url, err := buildUrl("_node/_local/_config", section, option)
if err != nil {
return "", err
}
resp, err := conn.request("GET", url, nil, nil, auth)
var val interface{}
parseBody(resp, &val)
if num, ok := val.(int); ok == true {
return strconv.Itoa(num), nil
}
if str, ok := val.(string); ok == true {
return str, nil
}
return "", nil
}
type UserRecord struct {
Name string `json:"name"`
Password string `json:"password,omitempty"`
Roles []string `json:"roles"`
TheType string `json:"type"` //apparently type is a keyword in Go :)
}
//Add a User.
//This is a convenience method for adding a simple user to CouchDB.
//If you need a User with custom fields, etc., you'll just have to use the
//ordinary document methods on the "_users" database.
func (conn *Connection) AddUser(username string, password string,
roles []string, auth Auth) (string, error) {
userData := UserRecord{
Name: username,
Password: password,
Roles: roles,
TheType: "user"}
userDb := conn.SelectDB("_users", auth)
namestring := "org.couchdb.user:" + userData.Name
return userDb.Save(&userData, namestring, "")
}
//Grants a role to a user
func (conn *Connection) GrantRole(username string, role string,
auth Auth) (string, error) {
userDb := conn.SelectDB("_users", auth)
namestring := "org.couchdb.user:" + username
var userData interface{}
rev, err := userDb.Read(namestring, &userData, nil)
if err != nil {
return "", err
}
if reflect.ValueOf(userData).Kind() != reflect.Map {
return "", errors.New("Type Error")
}
userMap := userData.(map[string]interface{})
if reflect.ValueOf(userMap["roles"]).Kind() != reflect.Slice {
return "", errors.New("Type Error")
}
userRoles := userMap["roles"].([]interface{})
//Check if our role is already in the array, so we don't add it twice
for _, r := range userRoles {
if r == role {
return rev, nil
}
}
userMap["roles"] = append(userRoles, role)
return userDb.Save(&userMap, namestring, rev)
}
//Revoke a user role
func (conn *Connection) RevokeRole(username string, role string,
auth Auth) (string, error) {
userDb := conn.SelectDB("_users", auth)
namestring := "org.couchdb.user:" + username
var userData interface{}
rev, err := userDb.Read(namestring, &userData, nil)
if err != nil {
return "", err
}
if reflect.ValueOf(userData).Kind() != reflect.Map {
return "", errors.New("Type Error")
}
userMap := userData.(map[string]interface{})
if reflect.ValueOf(userMap["roles"]).Kind() != reflect.Slice {
return "", errors.New("Type Error")
}
userRoles := userMap["roles"].([]interface{})
found := false
for i, r := range userRoles {
if r == role {
userRoles = append(userRoles[:i], userRoles[i+1:]...)
found = true
break
}
}
userMap["roles"] = userRoles
if found == false {
return "", nil
} else {
return userDb.Save(&userMap, namestring, rev)
}
}
type UserContext struct {
Name string `json:"name"`
Roles []string `json:"roles"`
}
type AuthInfo struct {
Authenticated string `json:"authenticated"`
AuthenticationDb string `json:"authentication_db"`
AuthenticationHandlers []string `json:"authentication_handlers"`
}
type AuthInfoResponse struct {
Info AuthInfo `json:"info"`
Ok bool `json:"ok"`
UserCtx UserContext `json:"userCtx"`
}
//Creates a session using the Couchdb session api. Returns auth token on success
func (conn *Connection) CreateSession(username string,
password string) (*CookieAuth, error) {
sessUrl, err := buildUrl("_session")
if err != nil {
return &CookieAuth{}, err
}
var headers = make(map[string]string)
body := "name=" + username + "&password=" + password
headers["Content-Type"] = "application/x-www-form-urlencoded"
resp, err := conn.request("POST", sessUrl,
strings.NewReader(body), headers, nil)
if err != nil {
return &CookieAuth{}, err
}
defer resp.Body.Close()
authToken := func() string {
for _, cookie := range resp.Cookies() {
if cookie.Name == "AuthSession" {
return cookie.Value
}
}
return ""
}()
return &CookieAuth{AuthToken: authToken}, nil
}
//Destroys a session (user log out, etc.)
func (conn *Connection) DestroySession(auth *CookieAuth) error {
sessUrl, err := buildUrl("_session")
if err != nil {
return err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
resp, err := conn.request("DELETE", sessUrl, nil, headers, auth)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
//Returns auth information for a user
func (conn *Connection) GetAuthInfo(auth Auth) (*AuthInfoResponse, error) {
authInfo := AuthInfoResponse{}
sessUrl, err := buildUrl("_session")
if err != nil {
return nil, err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
resp, err := conn.request("GET", sessUrl, nil, headers, auth)
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = parseBody(resp, &authInfo)
if err != nil {
return nil, err
}
return &authInfo, nil
}
//Fetch a user record
func (conn *Connection) GetUser(username string, userData interface{},
auth Auth) (string, error) {
userDb := conn.SelectDB("_users", auth)
namestring := "org.couchdb.user:" + username
return userDb.Read(namestring, &userData, nil)
}
//Delete a user.
func (conn *Connection) DeleteUser(username string, rev string, auth Auth) (string, error) {
userDb := conn.SelectDB("_users", auth)
namestring := "org.couchdb.user:" + username
return userDb.Delete(namestring, rev)
}
//Select a Database.
func (conn *Connection) SelectDB(dbName string, auth Auth) *Database {
return &Database{
dbName: dbName,
connection: conn,
auth: auth,
}
}
//DbExists checks if the database exists
func (db *Database) DbExists() error {
resp, err := db.connection.request("HEAD", "/"+db.dbName, nil, nil, db.auth)
if err != nil {
if resp != nil {
resp.Body.Close()
}
}
return err
}
//Compact the current database.
func (db *Database) Compact() (resp string, e error) {
url, err := buildUrl(db.dbName, "_compact")
fmt.Println(url)
if err != nil {
return "", err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
emtpyBody := ""
dbResponse, err := db.connection.request("POST", url, strings.NewReader(emtpyBody), headers, db.auth)
defer dbResponse.Body.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(dbResponse.Body)
strResp := buf.String()
return strResp, err
}
//Save a document to the database.
//If you're creating a new document, pass an empty string for rev.
//If updating, you must specify the current rev.
//Returns the revision number assigned to the doc by CouchDB.
func (db *Database) Save(doc interface{}, id string, rev string) (string, error) {
url, err := buildUrl(db.dbName, id)
if err != nil {
return "", err
}
var headers = make(map[string]string)
headers["Content-Type"] = "application/json"
headers["Accept"] = "application/json"
if id == "" {
return "", fmt.Errorf("No ID specified")
}
if rev != "" {
headers["If-Match"] = rev
}
data, numBytes, err := encodeData(doc)
if err != nil {
return "", err
}
headers["Content-Length"] = strconv.Itoa(numBytes)
//Yes, this needs to be here.
//Yes, I know the Golang http.Client doesn't support expect/continue
//This is here to work around a bug in CouchDB. It shouldn't work, and yet it does.
//See: http://stackoverflow.com/questions/30541591/large-put-requests-from-go-to-couchdb
//Also, I filed a bug report: https://issues.apache.org/jira/browse/COUCHDB-2704
//Go net/http needs to support the HTTP/1.1 spec, or CouchDB needs to get fixed.
//If either of those happens in the future, I can revisit this.
//Unless I forget, which I'm sure I will.
if numBytes > 4000 {
headers["Expect"] = "100-continue"
}
resp, err := db.connection.request("PUT", url, data, headers, db.auth)
if err != nil {
return "", err
}
defer resp.Body.Close()
return getRevInfo(resp)
}
//Copies a document into a new... document.
//Returns the revision of the newly created document
func (db *Database) Copy(fromId string, fromRev string, toId string) (string, error) {
url, err := buildUrl(db.dbName, fromId)
if err != nil {
return "", err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
if fromId == "" || toId == "" {
return "", fmt.Errorf("Invalid request. Ids must be specified")
}
if fromRev != "" {
headers["If-Match"] = fromRev
}
headers["Destination"] = toId
resp, err := db.connection.request("COPY", url, nil, headers, db.auth)
if err != nil {
return "", err
}
defer resp.Body.Close()
return getRevInfo(resp)
}
//Fetches a document from the database.
//Pass it a &struct to hold the contents of the fetched document (doc).
//Returns the current revision and/or error
func (db *Database) Read(id string, doc interface{}, params *url.Values) (string, error) {
var headers = make(map[string]string)
headers["Accept"] = "application/json"
var url string
var err error
if params == nil {
url, err = buildUrl(db.dbName, id)
} else {
url, err = buildParamUrl(*params, db.dbName, id)
}
if err != nil {
return "", err
}
resp, err := db.connection.request("GET", url, nil, headers, db.auth)
if err != nil {
return "", err
}
defer resp.Body.Close()
if err = parseBody(resp, &doc); err != nil {
return "", err
}
return getRevInfo(resp)
}
//Fetches multiple documents in a single request given a set of arbitrary _ids
func (db *Database) ReadMultiple(ids []string, results interface{}) error {
type RequestBody struct {
Keys []string `json:"keys"`
}
parameters := url.Values{}
parameters.Set("include_docs", "true")
url, err := buildParamUrl(parameters, db.dbName, "_all_docs")
if err != nil {
return err
}
var headers = make(map[string]string)
reqBody := RequestBody{Keys: ids}
requestBody, numBytes, err := encodeData(reqBody)
if err != nil {
return err
}
headers["Content-Type"] = "application/json"
headers["Content-Length"] = strconv.Itoa(numBytes)
if numBytes > 4000 {
headers["Expect"] = "100-continue"
}
headers["Accept"] = "application/json"
if resp, err :=
db.connection.request("POST", url, requestBody,
headers, db.auth); err == nil {
defer resp.Body.Close()
return parseBody(resp, &results)
} else {
return err
}
}
//Deletes a document.
//Or rather, tells CouchDB to mark the document as deleted.
//Yes, CouchDB will return a new revision, so this function returns it.
func (db *Database) Delete(id string, rev string) (string, error) {
url, err := buildUrl(db.dbName, id)
if err != nil {
return "", err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
headers["If-Match"] = rev
resp, err := db.connection.request("DELETE", url, nil, headers, db.auth)
if err != nil {
return "", err
}
defer resp.Body.Close()
return getRevInfo(resp)
}
//Saves an attachment.
//docId and docRev refer to the parent document.
//attType is the MIME type of the attachment (ex: image/jpeg) or some such.
//attContent is a byte array containing the actual content.
func (db *Database) SaveAttachment(docId string,
docRev string, attName string,
attType string, attContent io.Reader) (string, error) {
url, err := buildUrl(db.dbName, docId, attName)
if err != nil {
return "", err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
headers["Content-Type"] = attType
headers["If-Match"] = docRev
headers["Expect"] = "100-continue"
resp, err := db.connection.request("PUT", url, attContent, headers, db.auth)
if err != nil {
return "", err
}
defer resp.Body.Close()
return getRevInfo(resp)
}
//Gets an attachment.
//Returns an io.Reader -- the onus is on the caller to close it.
//Please close it.
func (db *Database) GetAttachment(docId string, docRev string,
attType string, attName string) (io.ReadCloser, error) {
url, err := buildUrl(db.dbName, docId, attName)
if err != nil {
return nil, err
}
var headers = make(map[string]string)
headers["Accept"] = attType
if docRev != "" {
headers["If-Match"] = docRev
}
resp, err := db.connection.request("GET", url, nil, headers, db.auth)
if err != nil {
return nil, err
}
return resp.Body, nil
}
//Fetches an attachment and proxies the result
func (db *Database) GetAttachmentByProxy(docId string, docRev string,
attType string, attName string, r *http.Request, w http.ResponseWriter) error {
path, err := buildUrl(db.dbName, docId, attName)
if err != nil {
return err
}
var headers = make(map[string]string)
headers["Accept"] = attType
if docRev != "" {
headers["If-Match"] = docRev
}
for k, v := range headers {
r.Header.Set(k, v)
}
return db.connection.reverseProxyRequest(w, r, path, db.auth)
}
//Deletes an attachment
func (db *Database) DeleteAttachment(docId string, docRev string,
attName string) (string, error) {
url, err := buildUrl(db.dbName, docId, attName)
if err != nil {
return "", err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
headers["If-Match"] = docRev
resp, err := db.connection.request("DELETE", url, nil, headers, db.auth)
if err != nil {
return "", err
}
defer resp.Body.Close()
return getRevInfo(resp)
}
type Members struct {
Users []string `json:"names,omitempty"`
Roles []string `json:"roles,omitempty"`
}
type Security struct {
Members Members `json:"members"`
Admins Members `json:"admins"`
}
//Returns the Security document from the database.
func (db *Database) GetSecurity() (*Security, error) {
url, err := buildUrl(db.dbName, "_security")
if err != nil {
return nil, err
}
var headers = make(map[string]string)
sec := Security{}
headers["Accept"] = "application/json"
resp, err := db.connection.request("GET", url, nil, headers, db.auth)
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = parseBody(resp, &sec)
if err != nil {
return nil, err
}
return &sec, err
}
//Save a security document to the database.
func (db *Database) SaveSecurity(sec Security) error {
url, err := buildUrl(db.dbName, "_security")
if err != nil {
return err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
data, numBytes, err := encodeData(sec)
if err != nil {
return err
}
headers["Content-Length"] = strconv.Itoa(numBytes)
if numBytes > 4000 {
headers["Expect"] = "100-continue"
}
resp, err := db.connection.request("PUT", url, data, headers, db.auth)
if err == nil {
resp.Body.Close()
}
return err
}
// Security helper function.
// Adds a role to a database security doc.
func (db *Database) AddRole(role string, isAdmin bool) error {
sec, err := db.GetSecurity()
if err != nil {
return err
}
roles := func() *[]string {
if isAdmin {
return &sec.Admins.Roles
} else {
return &sec.Members.Roles
}
}
//Make sure the role isn't already there (couchdb will let you add it twice :/ )
for _, r := range *roles() {
if r == role {
//already there, just return
return nil
}
}
rolesarr := roles()
*rolesarr = append(*rolesarr, role)
return db.SaveSecurity(*sec)
}
// Security helper function.
// Removes a role from a database security doc.
func (db *Database) RemoveRole(role string) error {
sec, err := db.GetSecurity()
if err != nil {
return err
}
remove := func(isAdmin bool) bool {
var rolesPtr *[]string
if isAdmin {
rolesPtr = &sec.Admins.Roles
} else {
rolesPtr = &sec.Members.Roles
}
roles := *rolesPtr
for i, r := range roles {
if r == role {
*rolesPtr = append(roles[:i], roles[i+1:]...)
return true
}
}
return false
}
var removed bool = false
if removed = remove(false); !removed {
removed = remove(true)
}
if removed {
return db.SaveSecurity(*sec)
}
return nil
}
//Get the results of a view.
func (db *Database) GetView(designDoc string, view string,
results interface{}, params *url.Values) error {
var err error
var url string
if params == nil {
url, err = buildUrl(db.dbName, "_design", designDoc, "_view", view)
} else {
url, err = buildParamUrl(*params, db.dbName, "_design",
designDoc, "_view", view)
}
if err != nil {
return err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
resp, err := db.connection.request("GET", url, nil, headers, db.auth)
if err != nil {
return err
}
defer resp.Body.Close()
err = parseBody(resp, &results)
if err != nil {
return err
}
return nil
}
//Get multiple results of a view.
func (db *Database) GetMultipleFromView(designDoc string, view string,
results interface{}, keys []string) error {
var err error
var url string
type RequestBody struct {
Keys []string `json:"keys"`
}
url, err = buildUrl(db.dbName, "_design", designDoc, "_view", view)
if err != nil {
return err
}
fmt.Errorf("url: " + url)
var headers = make(map[string]string)
reqBody := RequestBody{Keys: keys}
requestBody, numBytes, err := encodeData(reqBody)
if err != nil {
return err
}
headers["Content-Type"] = "application/json"
headers["Content-Length"] = strconv.Itoa(numBytes)
if numBytes > 4000 {
headers["Expect"] = "100-continue"
}
headers["Accept"] = "application/json"
if resp, err :=
db.connection.request("POST", url, requestBody,
headers, db.auth); err == nil {
defer resp.Body.Close()
return parseBody(resp, &results)
} else {
return err
}
}
//Get the result of a list operation
//This assumes your list function in couchdb returns JSON
func (db *Database) GetList(designDoc string, list string,
view string, results interface{}, params *url.Values) error {
var err error
var url string
if params == nil {
url, err = buildUrl(db.dbName, "_design", designDoc, "_list",
list, view)
} else {
url, err = buildParamUrl(*params, db.dbName, "_design", designDoc,
"_list", list, view)
}
if err != nil {
return err
}
var headers = make(map[string]string)
headers["Accept"] = "application/json"
resp, err := db.connection.request("GET", url, nil, nil, db.auth)
if err != nil {
return err
}
defer resp.Body.Close()
err = parseBody(resp, &results)
if err != nil {
return err
}
return nil
}
type FindQueryParams struct {
Selector interface{} `json:"selector"`
Limit int `json:"limit,omitempty"`
Skip int `json:"skip,omitempty"`
Sort interface{} `json:"sort,omitempty"`
Fields []string `json:"fields,omitempty"`
UseIndex interface{} `json:"user_index,omitempty"`
}
func (db *Database) Find(params *FindQueryParams) ([]byte, error) {
var err error
var url string
var results []byte
url, err = buildUrl(db.dbName, "_find")
if err != nil {
return results, err
}
requestBody, numBytes, err := encodeData(params)
if err != nil {
return results, err
}
var headers = make(map[string]string)
headers["Content-Type"] = "application/json"
headers["Accept"] = "application/json"
headers["Content-Length"] = strconv.Itoa(numBytes)
resp, err := db.connection.request("POST", url, requestBody, headers, db.auth)
if err != nil {
return results, err
}
defer resp.Body.Close()
err = parseBody(resp, &results)
if err != nil {
return results, err
}
return results, nil
}
//Save a design document.
//If creating a new design doc, set rev to "".
func (db *Database) SaveDesignDoc(name string,
designDoc interface{}, rev string) (string, error) {
path := "_design/" + name
newRev, err := db.Save(designDoc, path, rev)
if err != nil {
return "", err
} else if newRev == "" {
return "", fmt.Errorf("CouchDB returned an empty revision string.")
}
return newRev, nil
}