1
0
mirror of https://gitlab.crans.org/nounous/ghostream.git synced 2025-06-27 11:28:51 +02:00

Use pkger to pack templates

This commit is contained in:
Alexandre Iooss
2020-09-28 17:36:40 +02:00
parent 92f44c981d
commit 7716898713
7 changed files with 58 additions and 4 deletions

View File

@ -3,11 +3,14 @@ package web
import (
"encoding/json"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
"github.com/markbates/pkger"
"github.com/pion/webrtc/v3"
"gitlab.crans.org/nounous/ghostream/internal/monitoring"
)
@ -29,7 +32,7 @@ var (
localSdpChan chan webrtc.SessionDescription
// Preload templates
templates = template.Must(template.ParseGlob("web/template/*.html"))
templates *template.Template
// Precompile regex
validPath = regexp.MustCompile("^\\/[a-z0-9_-]*\\/?$")
@ -115,12 +118,47 @@ func staticHandler(w http.ResponseWriter, r *http.Request) {
}
}
// Load templates with pkger
// templates will be packed in the compiled binary
func loadTemplates() error {
templates = template.New("")
return pkger.Walk("/web/template", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip non-templates
if info.IsDir() || !strings.HasSuffix(path, ".html") {
return nil
}
// Open file with pkger
f, err := pkger.Open(path)
if err != nil {
return err
}
// Read and parse template
temp, err := ioutil.ReadAll(f)
if err != nil {
return err
}
templates, err = templates.Parse(string(temp))
return err
})
}
// Serve HTTP server
func Serve(rSdpChan chan webrtc.SessionDescription, lSdpChan chan webrtc.SessionDescription, c *Options) {
remoteSdpChan = rSdpChan
localSdpChan = lSdpChan
cfg = c
// Load templates
if err := loadTemplates(); err != nil {
log.Fatalln("Failed to load templates:", err)
}
// Set up HTTP router and server
mux := http.NewServeMux()
mux.HandleFunc("/", viewerHandler)

View File

@ -7,10 +7,16 @@ import (
)
func TestViewerPageGET(t *testing.T) {
r, _ := http.NewRequest("GET", "", nil)
// Load templates
if err := loadTemplates(); err != nil {
t.Errorf("Failed to load templates: %v", err)
}
// Test GET request
r, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
http.HandlerFunc(viewerHandler).ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("Viewer page didn't return %v on GET", http.StatusOK)
t.Errorf("Viewer page returned %v != %v on GET", w.Code, http.StatusOK)
}
}