set_key_handler.go 1.3 KB

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