websockets talk

This commit is contained in:
Barak Michener 2015-02-07 14:22:40 -05:00
parent 8900500b35
commit 429ba99406
2 changed files with 47 additions and 0 deletions

View file

@ -11,6 +11,7 @@ import (
"text/template" "text/template"
"github.com/russross/blackfriday" "github.com/russross/blackfriday"
"golang.org/x/net/websocket"
fsnotify "gopkg.in/fsnotify.v1" fsnotify "gopkg.in/fsnotify.v1"
) )
@ -19,6 +20,7 @@ var SUFFIXES = [3]string{".md", ".mkd", ".markdown"}
var toc []string var toc []string
var tocMutex sync.Mutex var tocMutex sync.Mutex
var rootTmpl *template.Template var rootTmpl *template.Template
var pageTmpl *template.Template
var path string var path string
func init() { func init() {
@ -27,6 +29,10 @@ func init() {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
pageTmpl, err = template.New("page").Parse(pageTemplate)
if err != nil {
log.Fatal(err)
}
} }
func HasMarkdownSuffix(s string) bool { func HasMarkdownSuffix(s string) bool {
@ -65,6 +71,8 @@ func WatcherEventLoop(w *fsnotify.Watcher, done chan bool) {
log.Println("Event:", event) log.Println("Event:", event)
// TODO(barakmich): On directory creation, stat path if directory, and watch it. // TODO(barakmich): On directory creation, stat path if directory, and watch it.
if HasMarkdownSuffix(event.Name) { if HasMarkdownSuffix(event.Name) {
if event.Op == fsnotify.Write {
}
} }
case err := <-w.Errors: case err := <-w.Errors:
@ -87,6 +95,17 @@ func RootFunc(w http.ResponseWriter, r *http.Request) {
rootTmpl.Execute(w, string(bytes)) rootTmpl.Execute(w, string(bytes))
} }
func PageFunc(w http.ResponseWriter, r *http.Request) {
subpath := strings.TrimPrefix(r.RequestURI, "/md")
log.Println("New watcher on ", subpath)
pageTmpl.Execute(w, subpath)
}
func HandleListener(ws *websocket.Conn) {
fmt.Println("WEBSOCKET!", ws.Request().RequestURI)
ws.Close()
}
func main() { func main() {
path = os.Getenv("PWD") path = os.Getenv("PWD")
if len(os.Args) > 1 { if len(os.Args) > 1 {
@ -111,5 +130,7 @@ func main() {
fmt.Println(toc) fmt.Println(toc)
http.HandleFunc("/", RootFunc) http.HandleFunc("/", RootFunc)
http.HandleFunc("/md/", PageFunc)
http.Handle("/ws/", websocket.Handler(HandleListener))
http.ListenAndServe(":8080", nil) http.ListenAndServe(":8080", nil)
} }

26
page_template.go Normal file
View file

@ -0,0 +1,26 @@
package main
var pageTemplate = `
<html>
<head>
<title>LiveMarkdown</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
var ws = new WebSocket("ws://" + location.host + "/ws" + "{{.}}")
ws.onopen = function() {
$("body").Text("wooot")
}
ws.onmessage = function(evt) {
$("body").Text(evt)
}
ws.onclose = function() {
}
</script>
</head>
<body>
</body>
</html>
`