set_key_handler.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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/go-raft"
  7. "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", store.UndefIndex, store.UndefTerm)
  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", store.UndefIndex, store.UndefTerm)
  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 && len(prevValueArr) > 0 {
  27. c = &store.CompareAndSwapCommand{
  28. Key: key,
  29. Value: value,
  30. PrevValue: prevValueArr[0],
  31. ExpireTime: expireTime,
  32. }
  33. } else {
  34. c = &store.CreateCommand{
  35. Key: key,
  36. Value: value,
  37. ExpireTime: expireTime,
  38. Force: true,
  39. }
  40. }
  41. return s.Dispatch(c, w, req)
  42. }