github.com/ghodss/etcd@v0.3.1-0.20140417172404-cc329bfa55cb/mod/leader/v2/set_handler.go (about)

     1  package v2
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net/http"
     7  	"net/url"
     8  
     9  	etcdErr "github.com/coreos/etcd/error"
    10  	"github.com/coreos/etcd/third_party/github.com/gorilla/mux"
    11  )
    12  
    13  // setHandler attempts to set the current leader.
    14  func (h *handler) setHandler(w http.ResponseWriter, req *http.Request) error {
    15  	vars := mux.Vars(req)
    16  	name := req.FormValue("name")
    17  	if name == "" {
    18  		return etcdErr.NewError(etcdErr.EcodeNameRequired, "Set", 0)
    19  	}
    20  
    21  	// Proxy the request to the the lock service.
    22  	u, err := url.Parse(fmt.Sprintf("%s/mod/v2/lock/%s", h.addr, vars["key"]))
    23  	if err != nil {
    24  		return err
    25  	}
    26  	q := u.Query()
    27  	q.Set("value", name)
    28  	q.Set("ttl", req.FormValue("ttl"))
    29  	q.Set("timeout", req.FormValue("timeout"))
    30  	u.RawQuery = q.Encode()
    31  
    32  	r, err := http.NewRequest("POST", u.String(), nil)
    33  	if err != nil {
    34  		return err
    35  	}
    36  
    37  	// Close request if this connection disconnects.
    38  	closeNotifier, _ := w.(http.CloseNotifier)
    39  	stopChan := make(chan bool)
    40  	defer close(stopChan)
    41  	go func() {
    42  		select {
    43  		case <-closeNotifier.CloseNotify():
    44  			h.transport.CancelRequest(r)
    45  		case <-stopChan:
    46  		}
    47  	}()
    48  
    49  	// Read from the leader lock.
    50  	resp, err := h.client.Do(r)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	defer resp.Body.Close()
    55  	w.WriteHeader(resp.StatusCode)
    56  	io.Copy(w, resp.Body)
    57  	return nil
    58  }