This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathmove_handler.go
102 lines (74 loc) · 1.82 KB
/
move_handler.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
package main
import (
"net/http"
elektra "github.com/ElektraInitiative/libelektra/src/bindings/go-elektra/kdb"
)
// postMoveHandler moves all keys below the `source` key to the target key.
//
// Arguments:
// source the source key. URL path param.
// target the target key. JSON string POST body.
//
// Response Code:
// 204 No Content if succesfull.
// 400 Bad Request if either the source or target keys are invalid.
//
// Example: `curl -X POST -d '"user:/test/world"' localhost:33333/kdbMv/user/test/hello`
func (s *server) postMoveHandler(w http.ResponseWriter, r *http.Request) {
from := parseKeyNameFromURL(r)
to, err := stringBody(r)
if err != nil || from == "" || to == "" {
badRequest(w)
return
}
fromKey, err := elektra.NewKey(from)
if err != nil {
badRequest(w)
return
}
defer fromKey.Close()
toKey, err := elektra.NewKey(to)
if err != nil {
badRequest(w)
return
}
defer toKey.Close()
root := elektra.CommonKeyName(fromKey, toKey)
rootKey, err := elektra.NewKey(root)
if err != nil {
writeError(w, err) // this should not happen
return
}
defer rootKey.Close()
handle, conf := getHandle(r)
_, err = handle.Get(conf, rootKey)
if err != nil {
writeError(w, err)
return
}
oldConf := conf.Cut(fromKey)
defer oldConf.Close()
if oldConf.Len() < 1 {
noContent(w)
return
}
newConf := elektra.NewKeySet()
defer newConf.Close()
for _, k := range oldConf.ToSlice() {
newConf.AppendKey(renameKey(k, from, to))
}
newConf.Append(conf) // these are unrelated keys
err = set(handle, newConf, rootKey)
if err != nil {
writeError(w, err)
return
}
noContent(w)
}
func renameKey(k elektra.Key, from, to string) elektra.Key {
otherName := k.Name()
baseName := otherName[len(from):]
newKey := k.Duplicate(elektra.KEY_CP_ALL)
newKey.SetName(to + baseName)
return newKey
}