github.com/jpetazzo/etcd@v0.2.1-0.20140113055439-97f1363afac5/mod/lock/v2/renew_handler.go (about)

     1  package v2
     2  
     3  import (
     4  	"path"
     5  	"net/http"
     6  	"strconv"
     7  
     8  	"github.com/gorilla/mux"
     9  )
    10  
    11  // renewLockHandler attempts to update the TTL on an existing lock.
    12  // Returns a 200 OK if successful. Returns non-200 on error.
    13  func (h *handler) renewLockHandler(w http.ResponseWriter, req *http.Request) {
    14  	h.client.SyncCluster()
    15  
    16  	// Read the lock path.
    17  	vars := mux.Vars(req)
    18  	keypath := path.Join(prefix, vars["key"])
    19  
    20  	// Parse new TTL parameter.
    21  	ttl, err := strconv.Atoi(req.FormValue("ttl"))
    22  	if err != nil {
    23  		http.Error(w, "invalid ttl: " + err.Error(), http.StatusInternalServerError)
    24  		return
    25  	}
    26  
    27  	// Read and set defaults for index and value.
    28  	index := req.FormValue("index")
    29  	value := req.FormValue("value")
    30  	if len(index) == 0 && len(value) == 0 {
    31  		// The index or value is required.
    32  		http.Error(w, "renew lock error: index or value required", http.StatusInternalServerError)
    33  		return
    34  	}
    35  
    36  	if len(index) == 0 {
    37  		// If index is not specified then look it up by value.
    38  		resp, err := h.client.Get(keypath, true, true)
    39  		if err != nil {
    40  			http.Error(w, "renew lock index error: " + err.Error(), http.StatusInternalServerError)
    41  			return
    42  		}
    43  		nodes := lockNodes{resp.Node.Nodes}
    44  		node, _ := nodes.FindByValue(value)
    45  		if node == nil {
    46  			http.Error(w, "renew lock error: cannot find: " + value, http.StatusInternalServerError)
    47  			return
    48  		}
    49  		index = path.Base(node.Key)
    50  
    51  	} else if len(value) == 0 {
    52  		// If value is not specified then default it to the previous value.
    53  		resp, err := h.client.Get(path.Join(keypath, index), true, false)
    54  		if err != nil {
    55  			http.Error(w, "renew lock value error: " + err.Error(), http.StatusInternalServerError)
    56  			return
    57  		}
    58  		value = resp.Node.Value
    59  	}
    60  
    61  	// Renew the lock, if it exists.
    62  	_, err = h.client.Update(path.Join(keypath, index), value, uint64(ttl))
    63  	if err != nil {
    64  		http.Error(w, "renew lock error: " + err.Error(), http.StatusInternalServerError)
    65  		return
    66  	}
    67  }