github.com/kula/etcd@v0.2.1-0.20131226070625-e96234382ac0/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  	"github.com/gorilla/mux"
    10  )
    11  
    12  // setHandler attempts to set the current leader.
    13  func (h *handler) setHandler(w http.ResponseWriter, req *http.Request) {
    14  	vars := mux.Vars(req)
    15  	name := req.FormValue("name")
    16  	if name == "" {
    17  		http.Error(w, "leader name required", http.StatusInternalServerError)
    18  		return
    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  		http.Error(w, err.Error(), http.StatusInternalServerError)
    25  		return
    26  	}
    27  	q := u.Query()
    28  	q.Set("value", name)
    29  	q.Set("ttl", req.FormValue("ttl"))
    30  	q.Set("timeout", req.FormValue("timeout"))
    31  	u.RawQuery = q.Encode()
    32  
    33  	r, err := http.NewRequest("POST", u.String(), nil)
    34  	if err != nil {
    35  		http.Error(w, err.Error(), http.StatusInternalServerError)
    36  		return
    37  	}
    38  
    39  	// Close request if this connection disconnects.
    40  	closeNotifier, _ := w.(http.CloseNotifier)
    41  	stopChan := make(chan bool)
    42  	defer close(stopChan)
    43  	go func() {
    44  		select {
    45  		case <-closeNotifier.CloseNotify():
    46  			h.transport.CancelRequest(r)
    47  		case <-stopChan:
    48  		}
    49  	}()
    50  
    51  	// Read from the leader lock.
    52  	resp, err := h.client.Do(r)
    53  	if err != nil {
    54  		http.Error(w, "set leader http error: " + err.Error(), http.StatusInternalServerError)
    55  		return
    56  	}
    57  	defer resp.Body.Close()
    58  	w.WriteHeader(resp.StatusCode)
    59  	if resp.StatusCode != http.StatusOK {
    60  		w.Write([]byte("set leader error: "))
    61  	}
    62  	io.Copy(w, resp.Body)
    63  }