From 50f4f839d1be9ef2467e8e3719b92f6bdca740d0 Mon Sep 17 00:00:00 2001 From: Brad Moylan Date: Thu, 11 Nov 2021 11:18:01 -0800 Subject: [PATCH] Use %q to quote struct tag values --- jen/examples_test.go | 16 ++++++++++++++-- jen/tag.go | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/jen/examples_test.go b/jen/examples_test.go index d6316b5..3ecca04 100644 --- a/jen/examples_test.go +++ b/jen/examples_test.go @@ -1,9 +1,8 @@ package jen_test import ( - "fmt" - "bytes" + "fmt" . "github.com/dave/jennifer/jen" ) @@ -1295,6 +1294,19 @@ func ExampleTag() { // } } +func ExampleTag_withQuotesAndNewline() { + c := Type().Id("foo").Struct( + Id("A").String().Tag(map[string]string{"json": "a"}), + Id("B").Int().Tag(map[string]string{"json": "b", "bar": "the value of\nthe\"bar\" tag"}), + ) + fmt.Printf("%#v", c) + // Output: + // type foo struct { + // A string `json:"a"` + // B int `bar:"the value of\nthe \"bar\" tag" json:"b"` + // } +} + func ExampleNull_and_nil() { c := Func().Id("foo").Params( nil, diff --git a/jen/tag.go b/jen/tag.go index ad99aaf..2f1baa5 100644 --- a/jen/tag.go +++ b/jen/tag.go @@ -59,7 +59,7 @@ func (t tag) render(f *File, w io.Writer, s *Statement) error { if len(str) > 0 { str += " " } - str += fmt.Sprintf(`%s:"%s"`, k, v) + str += fmt.Sprintf(`%s:%q`, k, v) } if strconv.CanBackquote(str) {