server: replace go-bindata with stdlib embed.FS

This commit is contained in:
mappu 2023-05-17 17:24:47 +12:00
parent ad95ac219d
commit cb29cf83ac
3 changed files with 18 additions and 479 deletions

View File

@ -24,18 +24,9 @@ dist: \
_dist/contented-$(VERSION)-src.zip
clean:
if [ -f ./staticResources.go ] ; then rm ./staticResources.go ; fi
if [ -d ./build ] ; then rm -r ./build ; fi
if [ -f ./contented ] ; then rm ./contented ; fi
#
# Generated files
#
staticResources.go: static/ static/*
go-bindata -o staticResources.go -prefix static -pkg contented static
#
# Release artefacts
#

View File

@ -1,8 +1,9 @@
package contented
import (
"bytes"
"embed"
"encoding/json"
"io/fs"
"log"
"net/http"
"os"
@ -14,6 +15,9 @@ import (
bolt "go.etcd.io/bbolt"
)
//go:embed static
var staticAssets embed.FS
var SERVER_HEADER string = `contented/0.0.0-dev`
const DEFAULT_MAX_CONCURRENT_THUMBS = 16
@ -49,6 +53,7 @@ type Server struct {
startTime time.Time
thumbnailSem chan struct{}
metadataBucket []byte
staticDir fs.FS // interface
}
func NewServer(opts *ServerOptions) (*Server, error) {
@ -63,6 +68,8 @@ func NewServer(opts *ServerOptions) (*Server, error) {
log.Printf("Allowing %d concurrent thumbnails", s.opts.MaxConcurrentThumbs)
}
s.staticDir, _ = fs.Sub(staticAssets, `static`) // can't fail
// "fill" the thumbnailer semaphore
s.thumbnailSem = make(chan struct{}, s.opts.MaxConcurrentThumbs)
for i := 0; i < s.opts.MaxConcurrentThumbs; i += 1 {
@ -157,11 +164,17 @@ func (this *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Blanket allow (headers already set)
w.WriteHeader(200)
} else if r.Method == "GET" && r.URL.Path == `/` && this.opts.EnableHomepage {
http.Redirect(w, r, `/index.html`, http.StatusFound)
} else if r.Method == "GET" {
} else if static, err := Asset(r.URL.Path[1:]); err == nil && r.Method == "GET" && (this.opts.EnableHomepage || r.URL.Path != `/index.html`) {
http.ServeContent(w, r, r.URL.Path[1:], this.startTime, bytes.NewReader(static))
// Conditionally block homepage access
if !this.opts.EnableHomepage && (r.URL.Path == `/index.html` || r.URL.Path == `/`) {
http.Error(w, "Not found", 404)
return
}
// Serve static html/css/js assets
// http.FileServer transparently redirects index.html->/ internally
http.FileServer(http.FS(this.staticDir)).ServeHTTP(w, r)
} else {
http.Error(w, "Not found", 404)

File diff suppressed because one or more lines are too long