我正在使用go和beego构建微服务应用程序。我正在尝试将服务A的JSON响应传递给服务B,如下所示:
func (u *ServiceController) GetAll() {
req := httplib.Get("http://localhost/api/1/services")
str, err := req.String()
// str = {"id":1, "name":"some service"}
if err != nil {
fmt.Println(err)
}
u.Data["json"] = str
u.ServeJSON()
}
然而,当我发送响应时,我实际上是双json编码:
"{\"id\":\"1\",\"name\":\"some service\"}"
最后,这是我提出的解决方案:
func (u *ServiceController) GetAll() {
req := httplib.Get("http://localhost/api/1/services")
str, err := req.String()
if err != nil {
fmt.Println(err)
}
strToByte := []byte(str)
u.Ctx.Output.Header("Content-Type", "application/json")
u.Ctx.Output.Body(strToByte)
}
答案 0 :(得分:0)
尝试一下:
func (u *ServiceController) GetAll() {
req := httplib.Get("http://localhost/api/1/services")
str, err := req.Bytes()
// str = {"id":1, "name":"some service"}
if err != nil {
fmt.Println(err)
}
u.Ctx.Output.Header("Content-Type", "text/plain;charset=UTF-8")
u.Ctx.ResponseWriter.Write(str)
}
如果调用req.String()
,它将在json字符串中编码"
。我建议您通常使用[]byte
处理数据。