server.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. package server
  2. import (
  3. "net/http"
  4. "net/url"
  5. "github.com/coreos/go-raft"
  6. "github.com/gorilla/mux"
  7. )
  8. // The Server provides an HTTP interface to the underlying store.
  9. type Server interface {
  10. CommitIndex() uint64
  11. Term() uint64
  12. Dispatch(raft.Command, http.ResponseWriter, *http.Request)
  13. }
  14. // This is the default implementation of the Server interface.
  15. type server struct {
  16. http.Server
  17. raftServer *raft.Server
  18. name string
  19. url string
  20. tlsConf *TLSConfig
  21. tlsInfo *TLSInfo
  22. corsOrigins map[string]bool
  23. }
  24. // Creates a new Server.
  25. func New(name string, urlStr string, listenHost string, tlsConf *TLSConfig, tlsInfo *TLSInfo, raftServer *raft.Server) *Server {
  26. s := &server{
  27. Server: http.Server{
  28. Handler: mux.NewRouter(),
  29. TLSConfig: &tlsConf.Server,
  30. Addr: listenHost,
  31. },
  32. name: name,
  33. url: urlStr,
  34. tlsConf: tlsConf,
  35. tlsInfo: tlsInfo,
  36. raftServer: raftServer,
  37. }
  38. // Install the routes for each version of the API.
  39. s.installV1()
  40. return s
  41. }
  42. // The current Raft committed index.
  43. func (s *server) CommitIndex() uint64 {
  44. return c.raftServer.CommitIndex()
  45. }
  46. // The current Raft term.
  47. func (s *server) Term() uint64 {
  48. return c.raftServer.Term()
  49. }
  50. func (s *server) installV1() {
  51. s.handleFunc("/v1/keys/{key:.*}", v1.GetKeyHandler).Methods("GET")
  52. s.handleFunc("/v1/keys/{key:.*}", v1.SetKeyHandler).Methods("POST", "PUT")
  53. s.handleFunc("/v1/keys/{key:.*}", v1.DeleteKeyHandler).Methods("DELETE")
  54. s.handleFunc("/v1/watch/{key:.*}", v1.WatchKeyHandler).Methods("GET", "POST")
  55. }
  56. // Adds a server handler to the router.
  57. func (s *server) handleFunc(path string, f func(http.ResponseWriter, *http.Request, Server) error) *mux.Route {
  58. r := s.Handler.(*mux.Router)
  59. // Wrap the standard HandleFunc interface to pass in the server reference.
  60. return r.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
  61. // Log request.
  62. debugf("[recv] %s %s [%s]", req.Method, s.url, req.URL.Path, req.RemoteAddr)
  63. // Write CORS header.
  64. if s.OriginAllowed("*") {
  65. w.Header().Add("Access-Control-Allow-Origin", "*")
  66. } else if s.OriginAllowed(r.Header.Get("Origin")) {
  67. w.Header().Add("Access-Control-Allow-Origin", r.Header.Get("Origin"))
  68. }
  69. // Execute handler function and return error if necessary.
  70. if err := f(w, req, s); err != nil {
  71. if etcdErr, ok := err.(*etcdErr.Error); ok {
  72. debug("Return error: ", (*etcdErr).Error())
  73. etcdErr.Write(w)
  74. } else {
  75. http.Error(w, e.Error(), http.StatusInternalServerError)
  76. }
  77. }
  78. })
  79. }
  80. // Start to listen and response etcd client command
  81. func (s *server) ListenAndServe() {
  82. infof("etcd server [name %s, listen on %s, advertised url %s]", s.name, s.Server.Addr, s.url)
  83. if s.tlsConf.Scheme == "http" {
  84. fatal(s.Server.ListenAndServe())
  85. } else {
  86. fatal(s.Server.ListenAndServeTLS(s.tlsInfo.CertFile, s.tlsInfo.KeyFile))
  87. }
  88. }
  89. // Sets a comma-delimited list of origins that are allowed.
  90. func (s *server) AllowOrigins(origins string) error {
  91. // Construct a lookup of all origins.
  92. m := make(map[string]bool)
  93. for _, v := range strings.Split(cors, ",") {
  94. if v != "*" {
  95. if _, err := url.Parse(v); err != nil {
  96. return fmt.Errorf("Invalid CORS origin: %s", err)
  97. }
  98. }
  99. m[v] = true
  100. }
  101. s.corsOrigins = m
  102. return nil
  103. }
  104. // Determines whether the server will allow a given CORS origin.
  105. func (s *server) OriginAllowed(origin string) {
  106. return s.corsOrigins["*"] || s.corsOrigins[origin]
  107. }