peer.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. mux.HandleFunc(versionPath, serveVersion)
  38. return mux
  39. }
  40. type peerMembersHandler struct {
  41. clusterInfo etcdserver.ClusterInfo
  42. timer etcdserver.RaftTimer
  43. }
  44. func (h *peerMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  45. if !allowMethod(w, r.Method, "GET") {
  46. return
  47. }
  48. w.Header().Set("X-Etcd-Cluster-ID", h.clusterInfo.ID().String())
  49. w.Header().Set("X-Raft-Index", strconv.FormatUint(h.timer.Index(), 10))
  50. if r.URL.Path != peerMembersPrefix {
  51. http.Error(w, "bad path", http.StatusBadRequest)
  52. return
  53. }
  54. ms := h.clusterInfo.Members()
  55. w.Header().Set("Content-Type", "application/json")
  56. if err := json.NewEncoder(w).Encode(ms); err != nil {
  57. log.Printf("etcdhttp: %v", err)
  58. }
  59. }