couchdb

package module
v2.0.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 8, 2020 License: Apache-2.0 Imports: 22 Imported by: 38

README

Build Status Codecov GoDoc

Kivik CouchDB

CouchDB driver for Kivik.

Usage

This package provides an implementation of the github.com/go-kivik/kivik/driver interface. You must import the driver and can then use the full Kivik API. Please consult the Kivik wiki for complete documentation and coding examples.

package main

import (
    "context"

    "github.com/go-kivik/kivik"
    _ "github.com/go-kivik/couchdb" // The CouchDB driver
)

func main() {
    client, err := kivik.New(context.TODO(), "couch", "")
    // ...
}

License

This software is released under the terms of the Apache 2.0 license. See LICENCE.md, or read the full license.

Documentation

Overview

Package couchdb is a driver for connecting with a CouchDB server over HTTP.

General Usage

Use the `couch` driver name when using this driver. The DSN should be a full URL, likely with login credentials:

import (
    "github.com/go-kivik/kivik"
    _ "github.com/go-kivik/couchdb" // The CouchDB driver
)

client, err := kivik.New("couch", "http://username:password@127.0.0.1:5984/")

Options

The CouchDB driver generally interprets kivik.Options keys and values as URL query parameters. Values of the following types will be converted to their appropriate string representation when URL-encoded:

  • bool
  • string
  • []string
  • int, uint, uint8, uint16, uint32, uint64, int8, int16, int32, int64

Passing any other type will return an error.

The only exceptions to the above rule are:

  • the special option keys defined by the package constants `OptionFullCommit` and `OptionIfNoneMatch`. These options set the appropriate HTTP request headers rather than setting a URL parameter.
  • the `keys` key, when passed to a view query, will result in a POST query being done, rather than a GET, to accommodate an arbitrary number of keys.
  • the 'NoMultipartPut' option is interpreted by the Kivik CouchDB driver to disable multipart/related PUT uploads of attachments.
  • the 'NoMultipartGet' option is interpreted by the Kivik CouchDB driver to disable multipart/related GET downloads of attachments.

Authentication

The CouchDB driver supports a number of authentication methods. For most uses, you don't need to worry about authentication at all--just include authentication credentials in your connection DSN:

client, _ := kivik.New("couch", "http://user:password@localhost:5984/")

This will use Cookie authentication by default.

To use one of the explicit authentication mechanisms, you'll need to use kivik's Authenticate method. For example:

client, _ := kivik.New("couch", "http://localhost:5984/")
err := client.Authenticate(ctx, couchdb.BasicAuth("bob", "abc123"))

Multipart PUT

Normally, to include an attachment in a CouchDB document, it must be base-64 encoded, which leads to increased network traffic and higher CPU load. CouchDB also supports the option to upload multiple attachments in a single request using the 'multipart/related' content type. See http://docs.couchdb.org/en/stable/api/document/common.html#creating-multiple-attachments

As an experimental feature, this is now supported by the Kivik CouchDB driver as well. To take advantage of this capability, the `doc` argument to the Put() method must be either:

  • a map of type `map[string]interface{}`, with a key called `_attachments', and value of type `kivik.Attachments` or `*kivik.Attachments`
  • a struct, with a field having the tag `json:"_attachment"`, and the field having the type `kivik.Attachments` or `*kivik.Attachments`.

With this in place, the CouchDB driver will switch to `multipart/related` mode, sending each attachment in binary format, rather than base-64 encoding it.

To function properly, each attachment must have an accurate Size value. If the Size value is unset, the entirely attachment may be read to determine its size, prior to sending it over the network, leading to delays and unnecessary I/O and CPU usage. The simplest way to ensure efficiency is to use the NewAttachment() method, provided by this package. See the documentation on that method for proper usage.

Example:

file, _ := os.Open("/path/to/photo.jpg")
atts := &kivik.Attachments{
    "photo.jpg": NewAttachment("photo.jpg", "image/jpeg", file),
}
doc := map[string]interface{}{
    "_id":          "user123",
    "_attachments": atts,
}
rev, err := db.Put(ctx, "user123", doc)

To disable the `multipart/related` capabilities entirely, you may pass the `NoMultipartPut` option, with any value. This will fallback to the default of inline base-64 encoding the attachments. Example:

rev, err := db.Put(ctx, "user123", doc", kivik.Options{couchdb.NoMultipartPut: "xxx"})

If you find yourself wanting to disable this feature, due to bugs or performance, please consider filing a bug report against Kivik as well, so we can look for a solution that will allow using this optimization.

Index

Constants

View Source
const (
	// OptionFullCommit is the option key used to set the `X-Couch-Full-Commit`
	// header in the request when set to true.
	//
	// Example:
	//
	//    db.Put(ctx, "doc_id", doc, kivik.Options{couchdb.OptionFullCommit: true})
	OptionFullCommit = "X-Couch-Full-Commit"

	// OptionIfNoneMatch is an option key to set the If-None-Match header on
	// the request.
	//
	// Example:
	//
	//    row, err := db.Get(ctx, "doc_id", kivik.Options{couchdb.OptionIfNoneMatch: "1-xxx"})
	OptionIfNoneMatch = "If-None-Match"

	// NoMultipartPut instructs the Put() method not to use CouchDB's
	// multipart/related upload capabilities. This only affects PUT requests that
	// also include attachments.
	NoMultipartPut = "kivik:no-multipart-put"

	// NoMultipartGet instructs the Get() method not to use CouchDB's ability to
	// download attachments with the multipart/related media type. This only
	// affects GET requests that request attachments.
	NoMultipartGet = "kivik:no-multipart-get"
)
View Source
const (
	VendorCouchDB  = "The Apache Software Foundation"
	VendorCloudant = "IBM Cloudant"
)

Known vendor strings

View Source
const Couch1ConfigNode = "<Couch1Config>"

Couch1ConfigNode can be passed to any of the Config-related methods as the node name, to query the /_config endpoint in a CouchDB 1.x-compatible way.

View Source
const Version = "2.0.0-prerelease"

Version is the current version of this package.

Variables

This section is empty.

Functions

func NewAttachment

func NewAttachment(filename, contentType string, content io.Reader, size ...int64) (*kivik.Attachment, error)

NewAttachment is a convenience function, which sets the size of the attachment based on content. This is intended for creating attachments to be uploaded using multipart/related capabilities of Put(). The attachment size will be set to the first of the following found:

  1. `size`, if present. Only the first value is considered
  2. content.Len(), if implemented (i.e. *bytes.Buffer)
  3. content.Stat().Size(), if implemented (i.e. *os.File)
  4. Read the entire content into memory, to determine the size. This can use a lot of memory for large attachments. Please use a file, or specify the size directly instead.

Types

type Authenticator added in v1.7.0

type Authenticator interface {
	// contains filtered or unexported methods
}

Authenticator is a CouchDB authenticator. Direct use of the Authenticator interface is for advanced usage. Typically, it is sufficient to provide a username and password in the connecting DSN to perform authentication. Only use one of these provided authenticators if you have specific, special needs.

func BasicAuth

func BasicAuth(user, password string) Authenticator

BasicAuth provides support for HTTP Basic authentication.

func CookieAuth

func CookieAuth(user, password string) Authenticator

CookieAuth provides support for CouchDB cookie-based authentication.

func ProxyAuth

func ProxyAuth(user, secret string, roles []string, headers ...map[string]string) Authenticator

ProxyAuth provides support for Proxy authentication.

The `secret` argument represents the `couch_httpd_auth/secret` value configured on the CouchDB server. See https://docs.couchdb.org/en/stable/config/auth.html#couch_httpd_auth/secret If `secret` is the empty string, the X-Auth-CouchDB-Token header will not be set, to support disabling the `proxy_use_secret` server setting. See https://docs.couchdb.org/en/stable/config/auth.html#couch_httpd_auth/proxy_use_secret

The optional `headers` map may be passed to use non-standard header names. For instance, to use `X-User` in place of the `X-Auth-CouchDB-Username` header, pass a value of {"X-Auth-CouchDB-UserName": "X-User"}. The relevant headers are X-Auth-CouchDB-UserName, X-Auth-CouchDB-Roles, and X-Auth-CouchDB-Token.

See https://docs.couchdb.org/en/stable/api/server/authn.html?highlight=proxy%20auth#proxy-authentication

func SetCookie

func SetCookie(cookie *http.Cookie) Authenticator

SetCookie adds cookie to all outbound requests. This is useful when using kivik as a proxy.

func SetTransport added in v1.7.0

func SetTransport(t http.RoundTripper) Authenticator

SetTransport returns an authenticator that can be used to set a client connection's HTTP Transport. This can be used to control proxies, TLS configuration, keep-alives, compression, etc.

Example:

setXport := couchdb.SetTransport(&http.Transport{
    // .. custom config
})
client, _ := kivik.New( ... )
client.Authenticate(setXport)

type BulkGetError

type BulkGetError struct {
	ID     string `json:"id"`
	Rev    string `json:"rev"`
	Err    string `json:"error"`
	Reason string `json:"reason"`
}

BulkGetError represents an error for a single document returned by a GetBulk call.

func (*BulkGetError) Error

func (e *BulkGetError) Error() string

type Couch

type Couch struct {
	// If provided, UserAgent is appended to the User-Agent header on all
	// outbound requests.
	UserAgent string

	// If provided, HTTPClient will be used for requests to the CouchDB server.
	HTTPClient *http.Client
}

Couch represents the parent driver instance.

func (*Couch) NewClient

func (d *Couch) NewClient(dsn string) (driver.Client, error)

NewClient establishes a new connection to a CouchDB server instance. If auth credentials are included in the URL, they are used to authenticate using CookieAuth (or BasicAuth if compiled with GopherJS). If you wish to use a different auth mechanism, do not specify credentials here, and instead call Authenticate() later.

Directories

Path Synopsis
Package chttp provides a minimal HTTP driver backend for communicating with CouchDB servers.
Package chttp provides a minimal HTTP driver backend for communicating with CouchDB servers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL