-
Notifications
You must be signed in to change notification settings - Fork 15
/
config.go
79 lines (68 loc) · 2.56 KB
/
config.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
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
package couchdb
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"strings"
"github.com/go-kivik/couchdb/v4/chttp"
"github.com/go-kivik/kivik/v4/driver"
)
// 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.
const Couch1ConfigNode = "<Couch1Config>"
var _ driver.Configer = &client{}
func configURL(node string, parts ...string) string {
var components []string
if node == Couch1ConfigNode {
components = append(make([]string, 0, len(parts)+1),
"_config")
} else {
components = append(make([]string, 0, len(parts)+3), // nolint:gomnd
"_node", node, "_config",
)
}
components = append(components, parts...)
return "/" + strings.Join(components, "/")
}
func (c *client) Config(ctx context.Context, node string) (driver.Config, error) {
cf := driver.Config{}
err := c.Client.DoJSON(ctx, http.MethodGet, configURL(node), nil, &cf)
return cf, err
}
func (c *client) ConfigSection(ctx context.Context, node, section string) (driver.ConfigSection, error) {
sec := driver.ConfigSection{}
err := c.Client.DoJSON(ctx, http.MethodGet, configURL(node, section), nil, &sec)
return sec, err
}
func (c *client) ConfigValue(ctx context.Context, node, section, key string) (string, error) {
var value string
err := c.Client.DoJSON(ctx, http.MethodGet, configURL(node, section, key), nil, &value)
return value, err
}
func (c *client) SetConfigValue(ctx context.Context, node, section, key, value string) (string, error) {
body, _ := json.Marshal(value) // Strings never cause JSON marshaling errors
var old string
opts := &chttp.Options{
Body: io.NopCloser(bytes.NewReader(body)),
}
err := c.Client.DoJSON(ctx, http.MethodPut, configURL(node, section, key), opts, &old)
return old, err
}
func (c *client) DeleteConfigKey(ctx context.Context, node, section, key string) (string, error) {
var value string
err := c.Client.DoJSON(ctx, http.MethodDelete, configURL(node, section, key), nil, &value)
return value, err
}