Skip to content

Commit

Permalink
library support
Browse files Browse the repository at this point in the history
  • Loading branch information
maxence-charriere committed Jun 27, 2023
1 parent 9b47482 commit b08a3dc
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
26 changes: 25 additions & 1 deletion pkg/app/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ type Handler struct {
// DEFAULT: en.
Lang string

// The custom libraries to load with the page.
Libraries []Library

// The page title.
Title string

Expand Down Expand Up @@ -198,6 +201,7 @@ type Handler struct {

once sync.Once
etag string
libraries map[string][]byte
proxyResources map[string]ProxyResource
cachedProxyResources *memoryCache
cachedPWAResources *memoryCache
Expand All @@ -207,6 +211,7 @@ func (h *Handler) init() {
h.initVersion()
h.initStaticResources()
h.initImage()
h.initLibraries()
h.initLinks()
h.initScripts()
h.initServiceWorker()
Expand Down Expand Up @@ -238,6 +243,15 @@ func (h *Handler) initImage() {
}
}

func (h *Handler) initLibraries() {
libs := make(map[string][]byte)
for _, l := range h.Libraries {
path, script := l.Script()
libs[path] = []byte(script)
}
h.libraries = libs
}

func (h *Handler) initLinks() {
for i, path := range h.Preconnect {
h.Preconnect[i] = h.resolveStaticPath(path)
Expand Down Expand Up @@ -589,6 +603,11 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}

if library, ok := h.libraries[path]; ok && len(library) != 0 {
h.serveLibrary(w, r, library)
return
}

h.servePage(w, r)
}

Expand Down Expand Up @@ -910,10 +929,15 @@ func (h *Handler) servePage(w http.ResponseWriter, r *http.Request) {

w.Header().Set("Content-Length", strconv.Itoa(b.Len()))
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
w.Write(b.Bytes())
}

func (h *Handler) serveLibrary(w http.ResponseWriter, r *http.Request, library []byte) {
w.Header().Set("Content-Length", strconv.Itoa(len(library)))
w.Header().Set("Content-Type", "text/css")
w.Write(library)
}

func (h *Handler) resolvePackagePath(path string) string {
var b strings.Builder

Expand Down
8 changes: 8 additions & 0 deletions pkg/app/library.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package app

// The interface that describes a library that contains custom components.
type Library interface {
// Returns the script and its path. The script must be a standard
// CSS file.
Script() (path, script string)
}

0 comments on commit b08a3dc

Please sign in to comment.