chat/routes.go

74 lines
1.5 KiB
Go

package chat
import (
"bytes"
"io"
"net/http"
"path/filepath"
"github.com/elazarl/go-bindata-assetfs"
"github.com/gorilla/context"
"golang.org/x/net/websocket"
)
//go:generate go get github.com/jteeuwen/go-bindata/...
//go:generate go get github.com/elazarl/go-bindata-assetfs/...
//go:generate rm -vf static.go
//go:generate go-bindata -o static.go -pkg=chat static/...
var prefix map[string]string
func addRoutes(sm *http.ServeMux, chat *Chat, staticFiles string) {
prefix = map[string]string{
"static": "/static/",
"auth": "/api/v0/auth/",
"reset": "/api/v0/auth/reset/",
"logout": "/logout/",
}
if staticFiles == "" {
logs.Debug("embedded static file serving")
sm.Handle(
prefix["static"],
http.FileServer(
&assetfs.AssetFS{
Asset: Asset,
AssetDir: AssetDir,
},
),
)
sm.HandleFunc(
"/",
func(w http.ResponseWriter, req *http.Request) {
data, err := Asset("static/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
r := bytes.NewReader(data)
io.Copy(w, r)
},
)
} else {
logs.Debug("setting up dev mode static file serving")
sm.Handle(
prefix["static"],
http.StripPrefix(
prefix["static"],
http.FileServer(http.Dir(staticFiles)),
),
)
sm.HandleFunc(
"/",
func(w http.ResponseWriter, req *http.Request) {
http.ServeFile(w, req, filepath.Join(staticFiles, "index.html"))
},
)
}
sm.HandleFunc("/info/", info)
sm.Handle("/ws/", websocket.Handler(chat.userLoop))
context.ClearHandler(sm)
}