Skip to content

Commit

Permalink
Add CSP nonce. Resolves: maddalax#69
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelDev0ps committed Jan 15, 2025
1 parent 66b6dff commit 3a23e7e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
6 changes: 6 additions & 0 deletions framework/h/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down
8 changes: 5 additions & 3 deletions framework/h/renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit 3a23e7e

Please sign in to comment.