main.go 986 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "flag"
  7. "log"
  8. "net/http"
  9. "text/template"
  10. )
  11. var addr = flag.String("addr", ":8080", "http service address")
  12. var homeTemplate = template.Must(template.ParseFiles("home.html"))
  13. func serveHome(w http.ResponseWriter, r *http.Request) {
  14. log.Println(r.URL)
  15. if r.URL.Path != "/" {
  16. http.Error(w, "Not found", 404)
  17. return
  18. }
  19. if r.Method != "GET" {
  20. http.Error(w, "Method not allowed", 405)
  21. return
  22. }
  23. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  24. homeTemplate.Execute(w, r.Host)
  25. }
  26. func main() {
  27. flag.Parse()
  28. hub := newHub()
  29. go hub.run()
  30. http.HandleFunc("/", serveHome)
  31. http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
  32. serveWs(hub, w, r)
  33. })
  34. err := http.ListenAndServe(*addr, nil)
  35. if err != nil {
  36. log.Fatal("ListenAndServe: ", err)
  37. }
  38. }