ghostream/web/web.go

73 lines
2.1 KiB
Go
Raw Normal View History

2020-09-21 15:47:31 +00:00
package web
import (
"html/template"
"log"
"net/http"
"os"
2020-09-21 17:59:41 +00:00
"gitlab.crans.org/nounous/ghostream/internal/config"
2020-09-21 19:33:32 +00:00
"gitlab.crans.org/nounous/ghostream/monitoring"
2020-09-21 15:47:31 +00:00
)
// Preload templates
var templates = template.Must(template.ParseGlob("web/template/*.tmpl"))
// Handle site index and viewer pages
2020-09-21 18:38:21 +00:00
func viewerHandler(w http.ResponseWriter, r *http.Request, cfg *config.Config) {
// Data for template
data := struct {
Path string
Cfg *config.Config
}{Path: r.URL.Path[1:], Cfg: cfg}
// FIXME validation on path: https://golang.org/doc/articles/wiki/#tmp_11
2020-09-21 15:47:31 +00:00
// Render template
2020-09-21 18:38:21 +00:00
err := templates.ExecuteTemplate(w, "base", data)
2020-09-21 15:47:31 +00:00
if err != nil {
log.Println(err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
2020-09-21 19:33:32 +00:00
// Increment monitoring
monitoring.ViewerServed.Inc()
2020-09-21 15:47:31 +00:00
}
// Auth incoming stream
2020-09-21 18:38:21 +00:00
func streamAuthHandler(w http.ResponseWriter, r *http.Request, cfg *config.Config) {
2020-09-21 15:47:31 +00:00
// FIXME POST request only with "name" and "pass"
// if name or pass missing => 400 Malformed request
// else login in against LDAP or static users
http.Error(w, "Not implemented", 400)
}
// Handle static files
// We do not use http.FileServer as we do not want directory listing
2020-09-21 18:38:21 +00:00
func staticHandler(w http.ResponseWriter, r *http.Request, cfg *config.Config) {
2020-09-21 15:47:31 +00:00
path := "./web/" + r.URL.Path
if f, err := os.Stat(path); err == nil && !f.IsDir() {
http.ServeFile(w, r, path)
} else {
http.NotFound(w, r)
}
}
2020-09-21 18:38:21 +00:00
// Closure to pass configuration
func makeHandler(fn func(http.ResponseWriter, *http.Request, *config.Config), cfg *config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fn(w, r, cfg)
}
}
2020-09-21 17:59:41 +00:00
// ServeHTTP server
func ServeHTTP(cfg *config.Config) {
2020-09-21 15:47:31 +00:00
// Set up HTTP router and server
2020-09-21 19:33:32 +00:00
mux := http.NewServeMux()
mux.HandleFunc("/", makeHandler(viewerHandler, cfg))
mux.HandleFunc("/rtmp/auth", makeHandler(streamAuthHandler, cfg))
mux.HandleFunc("/static/", makeHandler(staticHandler, cfg))
log.Printf("Listening on http://%s/", cfg.Site.ListenAddress)
log.Fatal(http.ListenAndServe(cfg.Site.ListenAddress, mux))
2020-09-21 15:47:31 +00:00
}