isolate handlers
This commit is contained in:
@@ -1,8 +1,11 @@
|
||||
// Package block provides functionality to load HTML blocks with associated content, JavaScript, and CSS from the filesystem.
|
||||
// API Endpoint:
|
||||
// /api/block/{blockPath}
|
||||
// Example:
|
||||
// /api/block/header would load the block located at {BlockDir}/header/
|
||||
// API Endpoint:
|
||||
//
|
||||
// /api/block/{blockPath}
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// /api/block/header would load the block located at {BlockDir}/header/
|
||||
package block
|
||||
|
||||
import (
|
||||
@@ -13,6 +16,7 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"git.oblat.lv/alex/triggerssmith/internal/config"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type Block struct {
|
||||
@@ -21,23 +25,34 @@ type Block struct {
|
||||
CSS string `json:"css"`
|
||||
}
|
||||
|
||||
func LoadHtmlBlock(cfg *config.Config) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !cfg.Server.BlockConfig.Enabled {
|
||||
http.Error(w, "Block serving is disabled", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
type blockHandler struct {
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
blockPath := r.URL.Path[len("/api/block/"):]
|
||||
block, err := LoadBlock(blockPath, cfg)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(block.ToJSON()))
|
||||
func Route(config *config.Config) func(chi.Router) {
|
||||
h := &blockHandler{
|
||||
cfg: config,
|
||||
}
|
||||
return func(r chi.Router) {
|
||||
r.Get("/{blockPath}", h.handleBlock)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *blockHandler) handleBlock(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.cfg.Server.BlockConfig.Enabled {
|
||||
http.Error(w, "Block serving is disabled", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
blockPath := r.URL.Path[len("/api/block/"):]
|
||||
block, err := LoadBlock(blockPath, h.cfg)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(block.ToJSON()))
|
||||
}
|
||||
|
||||
// LoadBlock loads a block from the filesystem given its path and configuration.
|
||||
|
||||
Reference in New Issue
Block a user