forked from etcd-io/etcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set_handler.go
58 lines (51 loc) · 1.24 KB
/
set_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
package v2
import (
"fmt"
"io"
"net/http"
"net/url"
etcdErr "github.com/coreos/etcd/error"
"github.com/coreos/etcd/third_party/github.com/gorilla/mux"
)
// setHandler attempts to set the current leader.
func (h *handler) setHandler(w http.ResponseWriter, req *http.Request) error {
vars := mux.Vars(req)
name := req.FormValue("name")
if name == "" {
return etcdErr.NewError(etcdErr.EcodeNameRequired, "Set", 0)
}
// Proxy the request to the the lock service.
u, err := url.Parse(fmt.Sprintf("%s/mod/v2/lock/%s", h.addr, vars["key"]))
if err != nil {
return err
}
q := u.Query()
q.Set("value", name)
q.Set("ttl", req.FormValue("ttl"))
q.Set("timeout", req.FormValue("timeout"))
u.RawQuery = q.Encode()
r, err := http.NewRequest("POST", u.String(), nil)
if err != nil {
return err
}
// Close request if this connection disconnects.
closeNotifier, _ := w.(http.CloseNotifier)
stopChan := make(chan bool)
defer close(stopChan)
go func() {
select {
case <-closeNotifier.CloseNotify():
h.transport.CancelRequest(r)
case <-stopChan:
}
}()
// Read from the leader lock.
resp, err := h.client.Do(r)
if err != nil {
return err
}
defer resp.Body.Close()
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
return nil
}