peer.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "strconv"
  20. "github.com/coreos/etcd/etcdserver"
  21. "github.com/coreos/etcd/rafthttp"
  22. )
  23. const (
  24. peerMembersPrefix = "/members"
  25. )
  26. // NewPeerHandler generates an http.Handler to handle etcd peer (raft) requests.
  27. func NewPeerHandler(clusterInfo etcdserver.ClusterInfo, timer etcdserver.RaftTimer, raftHandler http.Handler) http.Handler {
  28. mh := &peerMembersHandler{
  29. clusterInfo: clusterInfo,
  30. timer: timer,
  31. }
  32. mux := http.NewServeMux()
  33. mux.HandleFunc("/", http.NotFound)
  34. mux.Handle(rafthttp.RaftPrefix, raftHandler)
  35. mux.Handle(rafthttp.RaftPrefix+"/", raftHandler)
  36. mux.Handle(peerMembersPrefix, mh)
  37. return mux
  38. }
  39. type peerMembersHandler struct {
  40. clusterInfo etcdserver.ClusterInfo
  41. timer etcdserver.RaftTimer
  42. }
  43. func (h *peerMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  44. if !allowMethod(w, r.Method, "GET") {
  45. return
  46. }
  47. w.Header().Set("X-Etcd-Cluster-ID", h.clusterInfo.ID().String())
  48. w.Header().Set("X-Raft-Index", strconv.FormatUint(h.timer.Index(), 10))
  49. if r.URL.Path != peerMembersPrefix {
  50. http.Error(w, "bad path", http.StatusBadRequest)
  51. return
  52. }
  53. ms := h.clusterInfo.Members()
  54. w.Header().Set("Content-Type", "application/json")
  55. if err := json.NewEncoder(w).Encode(ms); err != nil {
  56. log.Printf("etcdhttp: %v", err)
  57. }
  58. }