Description

I get []byte data which is raw json from cuelang functions. But i do not known how to set it to Gin response data to return http json response and do not destroy it's json format.

How to reproduce

util.go below

package util

import (
    "cuelang.org/go/cue"
    "cuelang.org/go/cue/cuecontext"
    "fmt"
    log "github.com/sirupsen/logrus"
)

func RenderCueTemplate(parameter []byte, template []byte) ([]byte, error) {
    ctx := cuecontext.New()
    config := fmt.Sprintf(string(template)+"\nparameter: %s\n", parameter)
    val := ctx.CompileString(config)
    if val.Err() != nil {
        errRet := fmt.Errorf("failed to compile cue template, err: %s", val.Err())
        log.Error(errRet)
        return nil, errRet
    }
    v := val.LookupPath(cue.ParsePath("output"))

    output, err := v.MarshalJSON()
    if err != nil {
        errRet := fmt.Errorf("failed to marshal cue output to json, err: %s", err.Error())
        log.Error(errRet)
        return nil, errRet
    }

    return output, nil
}

controller.go below

package controller

func ListApplications(c *gin.Context){
    ...
    output, err := util.RenderCueTemplate(apps, tpl)
    if err != nil {
        log.Error(err)
        util.NewErrorGenericHttpResponse(c, http.StatusBadRequest, err, nil)
        return
    }

    ctx.JSON(200, output)
}

Expectations

Expect response body below

{"total":0,"applications":[]}

Actual result

Actual response body (a base64 string)

"eyJ0b3RhbCI6MCwiYXBwbGljYXRpb25zIjpbXX0="

Environment

  • go version: 1.17
  • gin version (or commit ref): 1.8.1
  • operating system: CentOS 7.6

Comment From: ArenaSu

I add a discussion topic on cuelang project, too cuelang discussion

Comment From: Gasoid

Usually you should use gin.H


c.JSON(http.StatusOK, gin.H{
      "message": "pong",
    })