github.com/sym3tri/etcd@v0.2.1-0.20140422215517-a563d82f95d6/server/v1/set_key_handler.go (about)

     1  package v1
     2  
     3  import (
     4  	"net/http"
     5  
     6  	etcdErr "github.com/coreos/etcd/error"
     7  	"github.com/coreos/etcd/store"
     8  	"github.com/coreos/etcd/third_party/github.com/goraft/raft"
     9  	"github.com/coreos/etcd/third_party/github.com/gorilla/mux"
    10  )
    11  
    12  // Sets the value for a given key.
    13  func SetKeyHandler(w http.ResponseWriter, req *http.Request, s Server) error {
    14  	vars := mux.Vars(req)
    15  	key := "/" + vars["key"]
    16  
    17  	req.ParseForm()
    18  
    19  	// Parse non-blank value.
    20  	value := req.Form.Get("value")
    21  	if len(value) == 0 {
    22  		return etcdErr.NewError(200, "Set", s.Store().Index())
    23  	}
    24  
    25  	// Convert time-to-live to an expiration time.
    26  	expireTime, err := store.TTL(req.Form.Get("ttl"))
    27  	if err != nil {
    28  		return etcdErr.NewError(202, "Set", s.Store().Index())
    29  	}
    30  
    31  	// If the "prevValue" is specified then test-and-set. Otherwise create a new key.
    32  	var c raft.Command
    33  	if prevValueArr, ok := req.Form["prevValue"]; ok {
    34  		if len(prevValueArr[0]) > 0 {
    35  			// test against previous value
    36  			c = s.Store().CommandFactory().CreateCompareAndSwapCommand(key, value, prevValueArr[0], 0, expireTime)
    37  		} else {
    38  			// test against existence
    39  			c = s.Store().CommandFactory().CreateCreateCommand(key, false, value, expireTime, false)
    40  		}
    41  
    42  	} else {
    43  		c = s.Store().CommandFactory().CreateSetCommand(key, false, value, expireTime)
    44  	}
    45  
    46  	return s.Dispatch(c, w, req)
    47  }