websocket/examples/chat/main.go

44 lines
986 B
Go
Raw Normal View History

// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
2013-10-16 20:41:47 +04:00
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"log"
"net/http"
"text/template"
)
var addr = flag.String("addr", ":8080", "http service address")
2016-05-18 17:56:16 +03:00
var homeTemplate = template.Must(template.ParseFiles("home.html"))
2013-10-16 20:41:47 +04:00
func serveHome(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL)
2013-10-16 20:41:47 +04:00
if r.URL.Path != "/" {
http.Error(w, "Not found", 404)
return
}
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
2013-10-16 20:41:47 +04:00
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
2016-05-18 17:56:16 +03:00
homeTemplate.Execute(w, r.Host)
2013-10-16 20:41:47 +04:00
}
func main() {
flag.Parse()
hub := newHub()
go hub.run()
2013-10-16 20:41:47 +04:00
http.HandleFunc("/", serveHome)
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
serveWs(hub, w, r)
})
2013-10-16 20:41:47 +04:00
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}