How to print template which consists of double quotes as a client response using Gin Framework


(Pavan Kumar) #1

hey guys, im trying to execute a text template which contains a JSON , when i do c.JSON() to send it as a client response double quotes in the template " are displaying as \"

here is my template

package templates

//SecretJSON1 variable containing secret json
const SecretJSON1 = `{
“apiVersion”: “v1”,
“data”: {
“DB_PASS”: “{{.DBPass}}”,
“DB_USER”: “{{.DBUser}}”,
“S3_ACCESS_KEY”: “{{.S3AccessKey}}”,
“S3_SECRET_KEY”: “{{.S3SecretKey}}”,
“S3_CREDENTIALS_FILE”: “{{.S3FileCreds}}”,
“HASH_SALT”: “{{.HashSalt}}”
},
“kind”: “Secret”,
“metadata”: {
“name”: “{{.Name}}”,
“namespace”: “{{.Namespace}}”
},
“type”: “Opaque”
}

`
In POSTMAN its displaying as

your help is much appreciated, thank you


(Norbert Melzer) #2

Don’t render a template, but use a struct or map that you pass to c.JSON(), and create it in a way that it marshals into the required JSON.


(Pavan Kumar) #3

Yeah I know it works with structs. I have to do it using templates but I’m not able escape the double quotes


(Norbert Melzer) #4

Then you can’t use c.JSON() as I already said in another thread. You need to send a raw response and set the content type header on your own.


(Pavan Kumar) #5

Yes! I followed what you said in the other thread, and it worked fmt.Fprintf(c.Writer, result). But is there any way I could do it with using c.JSON()

Because I’m building an api which users will consume and I’m thinking fmt should barely be used in the entire codebase


(Norbert Melzer) #6

As soon as you pass a string to c.JSON it will be masrshaled into a JSON string. You say you do not want that, so you either can’t use a string or c.JSON.

Also there are other alternatives to fmt.F*. eg. io.WriteString(c.Writer, result).

I’m still the opinion, that handing a struct to c.JSON is the way to go though, as rendering a template might be more expensive than marshalling.


(Pavan Kumar) #7

Okay yeah I understand, thanks for your help