handler.go 1.2 KB

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