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

     1  package v1
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  	"strconv"
     7  
     8  	etcdErr "github.com/coreos/etcd/error"
     9  	"github.com/coreos/etcd/third_party/github.com/gorilla/mux"
    10  )
    11  
    12  // Watches a given key prefix for changes.
    13  func WatchKeyHandler(w http.ResponseWriter, req *http.Request, s Server) error {
    14  	var err error
    15  	vars := mux.Vars(req)
    16  	key := "/" + vars["key"]
    17  
    18  	// Create a command to watch from a given index (default 0).
    19  	var sinceIndex uint64 = 0
    20  	if req.Method == "POST" {
    21  		sinceIndex, err = strconv.ParseUint(string(req.FormValue("index")), 10, 64)
    22  		if err != nil {
    23  			return etcdErr.NewError(203, "Watch From Index", s.Store().Index())
    24  		}
    25  	}
    26  
    27  	// Start the watcher on the store.
    28  	watcher, err := s.Store().Watch(key, false, false, sinceIndex)
    29  	if err != nil {
    30  		return etcdErr.NewError(500, key, s.Store().Index())
    31  	}
    32  	event := <-watcher.EventChan
    33  
    34  	// Convert event to a response and write to client.
    35  	w.WriteHeader(http.StatusOK)
    36  	if req.Method == "HEAD" {
    37  		return nil
    38  	}
    39  	b, _ := json.Marshal(event.Response(s.Store().Index()))
    40  	w.Write(b)
    41  	return nil
    42  }