How to escape quotes in a Multiline String Template

hey guys, i need help in printing a double quotes in a text template.
here’s my template

package templates

//SecretJSON2 variable containing secret json
var SecretJSON2 = { \"apiVersion\": \"v1\", \"kind\": \"Secret\", \"metadata\": { \"name\": \"{{.Name}}\", \"namespace\": \"{{.Namespace}}\", }, \"type\": \"Opaque\", \"data\": { \"private.key\": \"{{.PrivateKey}}\", \"public.key\": \"{{.PublicKey}}\" } }

and also tried without backslash

package templates

//SecretJSON2 variable containing secret json
var SecretJSON2 = { "apiVersion": "v1", "kind": "Secret", "metadata": { "name": "{{.Name}}", "namespace": "{{.Namespace}}", }, "type": "Opaque", "data": { "private.key": "{{.PrivateKey}}", "public.key": "{{.PublicKey}}" } }

but the output on the postman looks like this

here’s my controller and i’m using Gin as framework

package controllers

import (

“bytes”

“encoding/json”

“html/template”

“siranga/models”

“siranga/templates”

“strings”

)

var secret2 models.Secrets2

//Secret2Controller function

func Secret2Controller(val byte) string {

tmpl := template.Must(template.New(“certificate-tmpl”).Parse(strings.Replace(templates.SecretJSON2, “\n”, “”, -1)))

err := json.Unmarshal(val, &secret2)

if err != nil {

panic(err)

}

var temp bytes.Buffer

err = tmpl.Execute(&temp, secret2)

result := temp.String()

return result

}

//Secrets2Handler to handle DeploymentController

func Secrets2Handler(c *gin.Context) {

value, err := ioutil.ReadAll(c.Request.Body)

if err != nil {

panic(err)

}

results := controllers.Secret2Controller(value)

fmt.Println(“result”, results)

c.JSON(http.StatusOK, results)

}

I’m expecting the output to be like this
{ “apiVersion”: “v1”,
“kind”: “Secret”,
“metadata”: {
“name”: “drupal-secret”,
“namespace”: “verizon”,
},
“type”: “Opaque”,
“data”: {
“private.key”: “1234567890-sdfghjkldfghjk45678”,
“public.key”: “sdfghjkjhg56789”
}
}

2 Likes

You are encoding a string that is already JSON to a JSON string.

No need to json.Marshal the secret…

2 Likes

so how should it be? could you please help me with it

2 Likes

c.JSON() calls json.Marshal. Either pass in something that marshals into what you want, or use a method on the context that does send the response as is, but then you’ll probably need to remember to set the encoding correctly.

2 Likes

Okay thanks for the help

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.