Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Response in Beego Controller

I'm a newbie to beego trying to get a JSON response on a route.

I have a controller defined as such.

package controllers

import (
    "github.com/astaxie/beego"
)

type ErrorController struct {
    beego.Controller
}

type ErrorJson struct {
    s string
    d string
}

func (this *ErrorController) Get() {

    var responseJson ErrorJson
    responseJson = ErrorJson{
        s: "asdf",
        d: "qwer",
    }

    this.Data["json"] = responseJson
    this.ServeJson()
}

My router is defined as

beego.Router("/api", &controllers.ErrorController{})

When I visit the route, I get an Empty JSON object without any properties.

{}

If I replace the json struct with a string, I get a response. So beego is aware of the controller and the method.

this.Data["json"] = "Hello World"

What am I doing wrong?

like image 492
GokulSrinivas Avatar asked Jan 07 '23 01:01

GokulSrinivas


2 Answers

You need to export the fields in ErrorJson by starting the name with an uppercase character. Use field tags to specify the lowercase names in the output.

type ErrorJson struct {
    S string `json:"s"`
    D string `json:"d"`
}

The encoding/json package and similar packages ignore unexported fields.

like image 141
Bayta Darell Avatar answered Jan 15 '23 22:01

Bayta Darell


The s & d, low case in golang is not visable.

like image 23
Bryce Avatar answered Jan 15 '23 21:01

Bryce