handler.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package v2
  2. import (
  3. "net/http"
  4. "path"
  5. "strconv"
  6. "sort"
  7. "github.com/gorilla/mux"
  8. "github.com/coreos/go-etcd/etcd"
  9. )
  10. const prefix = "/_etcd/mod/lock"
  11. // handler manages the lock HTTP request.
  12. type handler struct {
  13. *mux.Router
  14. client *etcd.Client
  15. }
  16. // NewHandler creates an HTTP handler that can be registered on a router.
  17. func NewHandler(addr string) (http.Handler) {
  18. h := &handler{
  19. Router: mux.NewRouter(),
  20. client: etcd.NewClient([]string{addr}),
  21. }
  22. h.StrictSlash(false)
  23. h.HandleFunc("/{key:.*}", h.getIndexHandler).Methods("GET")
  24. h.HandleFunc("/{key:.*}", h.acquireHandler).Methods("POST")
  25. h.HandleFunc("/{key_with_index:.*}", h.renewLockHandler).Methods("PUT")
  26. h.HandleFunc("/{key_with_index:.*}", h.releaseLockHandler).Methods("DELETE")
  27. return h
  28. }
  29. // extractResponseIndices extracts a sorted list of indicies from a response.
  30. func extractResponseIndices(resp *etcd.Response) []int {
  31. var indices []int
  32. for _, node := range resp.Node.Nodes {
  33. if index, _ := strconv.Atoi(path.Base(node.Key)); index > 0 {
  34. indices = append(indices, index)
  35. }
  36. }
  37. sort.Ints(indices)
  38. return indices
  39. }
  40. // findPrevIndex retrieves the previous index before the given index.
  41. func findPrevIndex(indices []int, idx int) int {
  42. var prevIndex int
  43. for _, index := range indices {
  44. if index == idx {
  45. break
  46. }
  47. prevIndex = index
  48. }
  49. return prevIndex
  50. }