Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

html/template: should escape JSON without using \x #33671

Open
carlmjohnson opened this issue Aug 15, 2019 · 2 comments

Comments

@carlmjohnson
Copy link
Contributor

commented Aug 15, 2019

What version of Go are you using (go version)?

go version go1.12.7 darwin/amd64

Does this issue reproduce with the latest release?

Yes.

What did you do?

Ran this snippet

package main

import (
	"html/template"
	"log"
	"os"
)

func main() {
	const tpl = `<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>{{ .Title }}</title>
	</head>
	<body>
		<script type="application/ld+json">
		{
			"@context": "http://schema.org",
			"@type": "WebPage",
			"name":"{{ .Title }}",
			"description": "{{ .Description }}"
		}
		</script>
	</body>
</html>`

	check := func(err error) {
		if err != nil {
			log.Fatal(err)
		}
	}
	t, err := template.New("webpage").Parse(tpl)
	check(err)

	data := struct {
		Title, Description string
	}{
		Title:       "<My \"Cool\" Page>",
		Description: "A \"Cool\" Page by 'Me'",
	}

	err = t.Execute(os.Stdout, data)
	check(err)
}

What did you expect to see?

An HTML document containing valid JSON.

What did you see instead?

Invalid JSON, as reported by https://search.google.com/structured-data/testing-tool/


Go escapes what is between the <script> tags as though it were JavaScript because of #26053. That's mostly correct, except that there are subtle difference between valid JavaScript and valid JSON. Specifically, https://search.google.com/structured-data/testing-tool/ reports that \x3c style escaping is not correct for LD JSON. It needs to be \u003c instead.

@carlmjohnson

This comment has been minimized.

Copy link
Contributor Author

commented Aug 15, 2019

FWIW, http://json.org agrees that \u escapes are valid JSON and \x escapes are not.

ISTM, the simple solution is to tell the JavaScript escaper to always use \u. JS and JSON have other differences around whitespace handing, but it's easy enough to make them compatible.

@carlmjohnson carlmjohnson changed the title html/template should recognize <script type="application/ld+json"> html/template should escape JSON without using \x Aug 15, 2019

@agnivade

This comment has been minimized.

Copy link
Member

commented Aug 16, 2019

@bcmills bcmills changed the title html/template should escape JSON without using \x html/template: should escape JSON without using \x Aug 19, 2019

@bcmills bcmills added this to the Go1.14 milestone Aug 19, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants
You can’t perform that action at this time.