lundi 7 mars 2016

GOlang reflection or alias in order to provide different output

So I have following structure:

type ExternalValue struct {
    ID bson.ObjectId `json: "_id" bson:"_id, omitempty"`
    Name string        `json: "name" bson: "name`
    UserId    bson.ObjectId `json: "userId" bson: "userId`
    UserName  string        `json: "userName" bson: "userName`
    Value     int64         `json: "value" bson: "value"`
    AddedTime time.Time     `json:"addedTime" bson:"addedTime"`
}

And I store values in mongo database and once when I fetch them I need to pass this as output to browser (using gin framework here)

So if I output 'allScores' from snippet below

type ExternalValues []ExternalValue    
allScores := ExternalValues{}
err := con.Find(bson.M{"name": someName}).Sort("-value").All(&allScores)

I will get in the end json representation which is visible in struct. What however I need to do is different output with minimal effort.

So instead of:

 { 
          "ID": "56dd8bfc0640fd0e6e6a7930",
          "Name": "someName",
          "UserId": "56dd8bfc0640fd0e6e6a7931",
          "UserName": "guest7485",
          "Value": 221,
          "addedTime": "2016-03-07T14:11:08.853Z"
 }

I would like to have (different output scenarios) for example:

{ 
         "ID": "56dd8bfc0640fd0e6e6a7930",
         "its_just_a_name": "someName",
         "user_id": "56dd8bfc0640fd0e6e6a7931",
         "user_name": "guest7485",
         "your_value": 221,
         "added_on": "2016-03-07T14:11:08.853Z"
 }

And so on.... I'm struggling with this, and if you have any examples how to achieve this I would be really thankful.





Aucun commentaire:

Enregistrer un commentaire