peer.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdhttp
  15. import (
  16. "encoding/json"
  17. "net/http"
  18. "github.com/coreos/etcd/etcdserver"
  19. "github.com/coreos/etcd/rafthttp"
  20. )
  21. const (
  22. peerMembersPrefix = "/members"
  23. )
  24. // NewPeerHandler generates an http.Handler to handle etcd peer (raft) requests.
  25. func NewPeerHandler(cluster etcdserver.Cluster, raftHandler http.Handler) http.Handler {
  26. mh := &peerMembersHandler{
  27. cluster: cluster,
  28. }
  29. mux := http.NewServeMux()
  30. mux.HandleFunc("/", http.NotFound)
  31. mux.Handle(rafthttp.RaftPrefix, raftHandler)
  32. mux.Handle(rafthttp.RaftPrefix+"/", raftHandler)
  33. mux.Handle(peerMembersPrefix, mh)
  34. mux.HandleFunc(versionPath, versionHandler(cluster, serveVersion))
  35. return mux
  36. }
  37. type peerMembersHandler struct {
  38. cluster etcdserver.Cluster
  39. }
  40. func (h *peerMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  41. if !allowMethod(w, r.Method, "GET") {
  42. return
  43. }
  44. w.Header().Set("X-Etcd-Cluster-ID", h.cluster.ID().String())
  45. if r.URL.Path != peerMembersPrefix {
  46. http.Error(w, "bad path", http.StatusBadRequest)
  47. return
  48. }
  49. ms := h.cluster.Members()
  50. w.Header().Set("Content-Type", "application/json")
  51. if err := json.NewEncoder(w).Encode(ms); err != nil {
  52. plog.Warningf("failed to encode members response (%v)", err)
  53. }
  54. }