web.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright 2013 CoreOS Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package web
  14. import (
  15. "code.google.com/p/go.net/websocket"
  16. "fmt"
  17. "github.com/coreos/go-raft"
  18. "html/template"
  19. "net/http"
  20. "net/url"
  21. )
  22. var mainTempl *template.Template
  23. var mainPage *MainPage
  24. type MainPage struct {
  25. Leader string
  26. Address string
  27. }
  28. func mainHandler(c http.ResponseWriter, req *http.Request) {
  29. p := mainPage
  30. mainTempl.Execute(c, p)
  31. }
  32. func Start(raftServer *raft.Server, webURL string) {
  33. u, _ := url.Parse(webURL)
  34. webMux := http.NewServeMux()
  35. server := &http.Server{
  36. Handler: webMux,
  37. Addr: u.Host,
  38. }
  39. mainPage = &MainPage{
  40. Leader: raftServer.Leader(),
  41. Address: u.Host,
  42. }
  43. mainTempl = template.Must(template.New("index.html").Parse(index_html))
  44. go h.run()
  45. webMux.HandleFunc("/", mainHandler)
  46. webMux.Handle("/ws", websocket.Handler(wsHandler))
  47. fmt.Printf("etcd web server [%s] listening on %s\n", raftServer.Name(), u)
  48. server.ListenAndServe()
  49. }