Add CSP nonce. Resolves: #69

This commit is contained in:
rafaelDev0ps 2025-01-14 21:32:18 -03:00
parent 66b6dfffd3
commit 3a23e7e566
2 changed files with 11 additions and 3 deletions

View file

@ -20,6 +20,12 @@ func WithDocType() RenderOpt {
}
}
func WithNonce(nonce string) RenderOpt {
return func(context *RenderContext, opt *RenderOptions) {
context.nonce = nonce
}
}
// Render renders the given node recursively, and returns the resulting string.
func Render(node Ren, opts ...RenderOpt) string {
builder := &strings.Builder{}

View file

@ -2,10 +2,11 @@ package h
import (
"fmt"
"github.com/maddalax/htmgo/framework/hx"
"html"
"html/template"
"strings"
"github.com/maddalax/htmgo/framework/hx"
)
type CustomElement = string
@ -44,16 +45,17 @@ type RenderContext struct {
builder *strings.Builder
scripts []ScriptEntry
currentElement *Element
nonce string
}
func (ctx *RenderContext) AddScript(funcName string, body string) {
script := fmt.Sprintf(`
<script id="%s">
<script id="%s" nonce="%s">
function %s(self, event) {
let e = event;
%s
}
</script>`, funcName, funcName, body)
</script>`, funcName, ctx.nonce, funcName, body)
ctx.scripts = append(ctx.scripts, ScriptEntry{
Body: script,