swaggo/swag

double brackets in field description causes template engine to fail

mainpart opened this issue · 4 comments

If i use {{ and }} syntax in field comments swagger fail to templatize document with neccessary variables to function.

type Struct struct{
Field1 string // you can use {{funcwhatever param}} in string value
}

swaggo successfully compiles docs.go but fails to template it because funcwhatever is not defined in runtime.
as a result html page become dysfunctional

// ReadDoc parses SwaggerTemplate into swagger document.
func (i *Spec) ReadDoc() string {
	i.Description = strings.Replace(i.Description, "\n", "\\n", -1)
         ...
	}).Parse(i.SwaggerTemplate)
	if err != nil {
		return i.SwaggerTemplate
	}

swag version 1.81

That's because ReadDoc renders a go template, and {{ and }} are used as delimiters.

You didn't use an issue template for reporting. Is this a feature request?

yes, i have figured that out about go text/template engine. The thing is - it was counter intuitive, what has been broken.

The arbitrary single go comment and swagger mailfunction is somewhat totally unrelated. In fact, swagger compiles correctly, it does not produces any errors. The error is only visible when you trying to operate WEB UI. And that error looks totally unrelated with comment. You even do not mention it to yourself that you changed something that may broke system when you typing comment. And then after some coding you run project and - bang! something happens! it does not run in browser!

after 2hr of overlooking into problem (removing swagger description here and there, trying to allocate the source of the problem) i finally debugged it with delve and found the root.

it's neither feature request, nor the bug. It's just a warning for someone who might lose some time by stumbling to unobvious thing.

Maybe WARNING note when parsing comment with special chars could fix that.

I will take a look later sometime at this thing. We may escape the parentheses to they would be ignored by the template engine.

Running in to a similar issue where we have a Struct tag with {{ in the "example" field:

 example:"http://example.com/some-url/{{ placeholder }}" swaggertype:"string"`

This silently broke the template parsing and took me way too long to figure out since if the Parse() call fails it just returns the raw "swagger.json" and doesn't log anything.

As @mainpart suggested, I too propose that some kind of error or warning is added, perhaps at swag's doc.go generation time.

I'd also like to add a way to customise the Go template's delimiters using the template.New().Delims() function.
I'll get a PR ready for the Delims change and see if it makes sense.

edit: done, #1499