peer.go 1.7 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. "log"
  18. "net/http"
  19. "github.com/coreos/etcd/etcdserver"
  20. "github.com/coreos/etcd/rafthttp"
  21. )
  22. const (
  23. peerMembersPrefix = "/members"
  24. )
  25. // NewPeerHandler generates an http.Handler to handle etcd peer (raft) requests.
  26. func NewPeerHandler(clusterInfo etcdserver.ClusterInfo, raftHandler http.Handler) http.Handler {
  27. mh := &peerMembersHandler{
  28. clusterInfo: clusterInfo,
  29. }
  30. mux := http.NewServeMux()
  31. mux.HandleFunc("/", http.NotFound)
  32. mux.Handle(rafthttp.RaftPrefix, raftHandler)
  33. mux.Handle(rafthttp.RaftPrefix+"/", raftHandler)
  34. mux.Handle(peerMembersPrefix, mh)
  35. return mux
  36. }
  37. type peerMembersHandler struct {
  38. clusterInfo etcdserver.ClusterInfo
  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.clusterInfo.ID().String())
  45. if r.URL.Path != peerMembersPrefix {
  46. http.Error(w, "bad path", http.StatusBadRequest)
  47. return
  48. }
  49. ms := h.clusterInfo.Members()
  50. w.Header().Set("Content-Type", "application/json")
  51. if err := json.NewEncoder(w).Encode(ms); err != nil {
  52. log.Printf("etcdhttp: %v", err)
  53. }
  54. }