Golang proper way to send json response with status - mysql

How to send json response with status code in response body.
My code
func getUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user []User
result := db.Find(&user)
json.NewEncoder(w).Encode(result)
}
My result now:
[
{
"name" : "test",
"age" : "28",
"email":"test#gmail.com"
},
{
"name" : "sss",
"age" : "60",
"email":"ss#gmail.com"
},
{
"name" : "ddd",
"age" : "30",
"email":"ddd#gmail.com"
},
]
But I need to send the response with status code like this
{
status : "success",
statusCode : 200,
data : [
{
"name" : "test",
"age" : "28",
"email":"test#gmail.com"
},
{
"name" : "sss",
"age" : "60",
"email":"ss#gmail.com"
},
{
"name" : "ddd",
"age" : "30",
"email":"ddd#gmail.com"
},
]
}

If you want different json, pass a different object to Encode.
type Response struct {
Status string `json:"status"`
StatucCode int `json:"statusCode"`
Data []User `json:"data"`
}
func getUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user []User
result := db.Find(&user)
json.NewEncoder(w).Encode(&Response{"success", 200, result})
}
Or use a map:
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "success",
"statusCode": 200,
"data": result,
})

Related

How to send below body request to hit service and get response

{
"version": 46,
"actions": [
{
"action" : "addCustomLineItem",
"name" : {
"en" : "Global India"
},
"quantity" : 1,
"money" : {
"currencyCode" : "INR",
"centAmount" : 4200
},
"slug" : "mySlug",
"taxCategory" : {
"typeId" : "tax-category",
"id" : "20f5a0ca-e3fd-48b6-8258-8dc8c75fe22a"
}
}
]
}
Above is my body request.
And we have stored above data in cartIdData variable. I am not getting response. showing it does not contain valid json format.
this.cartIdData = {
version:this.cartversion,
productId:this.productID,
currency:this.currencycode,
price:this.priceparseInt,
cartaction:action,
india:this.name,
slugname:this.slugname
};

How to decode mongodb data to struct

Go Model:
package models
import (
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// News : News Model
type News struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Host string `json:"host,omitempty" bson:"host,omitempty"`
Category string `json:"category,omitempty" bson:"category,omitempty"`
Headline string `json:"headline,omitempty" bson:"headline,omitempty"`
Image string `json:"image,omitempty" bson:"image,omitempty"`
URL string `json:"url,omitempty" bson:"url,omitempty"`
Date string `json:"date,omitempty" bson:"date,omitempty"`
ClickCount int64 `json:"clickCount,omitempty" bson:"clickCount,omitempty"`
Archived bool `json:"archived,omitempty" bson:"archived,omitempty"`
CreatedAt time.Time `json:"createdAt,omitempty" bson:"createdAt,omitempty"`
}
MongoDB Data that I have:
{
"_id" : ObjectId("5e1d58f6fad87c735bbca592"),
"createdAt" : ISODate("2020-01-14T11:30:22.481Z"),
"clickCount" : 0,
"archived" : false,
"host" : "timesofindia",
"category" : "sports",
"headline" : "Caroline Wozniacki pulls out of Kooyong Classic",
"url" : "https://timesofindia.indiatimes.com/sports/tennis/top-stories/caroline-wozniacki-pulls-out-of-kooyong-classic/articleshow/73238147.cms",
"image" : "https://timesofindia.indiatimes.com/thumb/msid-73238147,width-400,resizemode-4/73238147.jpg",
"date" : "14 Jan 2020, 0958 hrs IST"
}
My API endpoint code:
func AllNews(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
collection := config.Client.Database("newspaper").Collection("news")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
var allNews []models.News
var finalResponse models.FinalResponse
cursor, e := collection.Find(ctx, bson.M{})
if e != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{ "message": "` + e.Error() + `" }`))
return
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var news models.News
cursor.Decode(&news)
allNews = append(allNews, news)
}
finalResponse.Status = "success"
finalResponse.Body = allNews
json.NewEncoder(w).Encode(finalResponse)
}
Challenge that I am facing right now is in output, I can not see "clickCount" and "archived".
Output:
{
"status": "success",
"body": [
{
"_id": "5e1d58f6fad87c735bbca588",
"host": "timesofindia",
"category": "business",
"headline": "Bandhan Bank all set to announce its Q3 results today",
"image": "https://timesofindia.indiatimes.com/thumb/msid-73239715,width-400,resizemode-4/73239715.jpg",
"url": "https://timesofindia.indiatimes.com/business/india-business/bandhan-bank-all-set-to-announce-its-q3-results-today/articleshow/73239715.cms",
"date": "14 Jan 2020, 1111 hrs IST",
"createdAt": "2020-01-14T11:30:22.442Z"
}
]
}
I tried changing data types to int32 and string on both fields it still didn't work.
If I change the data type of these two field then in "body" of output I only see "id" and "createdAt"
Let me know if more data is needed.
You should remove the clickCount and archived JSON tag omitempty

How to struct array in nested json object with the same keys

I am creating host objects in Zabbix via microservices in Golang. I have to serve the following json to
the Zabbix api to create host which is part of multiple groups
{
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": "TEST-HOST",
"interfaces": [
{
"type": 2,
"main": 1,
"useip": 1,
"ip": "0.0.0.0",
"dns": "",
"port": "10050"
}
],
"groups": [
{
"groupid": "33"
},
{
"groupid": "27"
}
],
"templates": [
{
"templateid": "12156"
}
],
"inventory_mode": 0
},
"auth": "example_token",
"id": 1
}
This code returns the json object where the groups array is empty.
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type Zabbix struct {
Jsonrpc string `json:"jsonrpc"`
Method string `json:"method"`
Params Params `json:"params"`
Auth string `json:"auth"`
ID int `json:"id"`
}
type Groups struct {
Groupid string `json:"groupid"`
Groupid1 string `json:"groupid"`
}
type Templates struct {
Templateid string `json:"templateid"`
}
type Inventory struct {
Type string `json:"type"`
Tag string `json:"tag"`
TypeFull string `json:"type_full"`
MacaddressA string `json:"macaddress_a"`
MacaddressB string `json:"macaddress_b"`
SerialA string `json:"serialno_a"`
SerialB string `json:"serialno_b"`
}
type Params struct {
Host string `json:"host"`
Interfaces []Interfaces `json:"interfaces"`
Groups []Groups `json:"groups"`
Templates []Templates `json:"templates"`
InventoryMode int `json:"inventory_mode"`
Inventory Inventory `json:"inventory"`
}
type Interfaces struct {
Type int `json:"type"`
Main int `json:"main"`
Useip int `json:"useip"`
IP string `json:"ip"`
DNS string `json:"dns"`
Port string `json:"port"`
}
func main() {
jsonobj := &Zabbix{
Jsonrpc: "2.0",
Method: "host.create",
Params: Params{
Host: "OBU_TEST_123",
Interfaces: []Interfaces{
{
Type: 2,
Main: 1,
Useip: 1,
IP: "10.10.10.10",
DNS: "",
Port: "10050",
},
},
Groups: []Groups{
{
Groupid: "27",
Groupid1: "33",
},
},
Templates: []Templates{
{
Templateid: "12156",
},
},
Inventory: Inventory{
Type: "On Board Unit",
Tag: "test",
TypeFull: "test",
MacaddressA: "test",
MacaddressB: "test",
SerialA: "test",
SerialB: "test",
},
InventoryMode: 0,
},
Auth: "test-token",
ID: 1,
}
byteArray, err := json.Marshal(jsonobj)
if err != nil {
panic(err)
}
fmt.Print(bytes.NewBuffer(byteArray).String())
}
The output:
{
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": "OBU_TEST_123",
"interfaces": [
{
"type": 2,
"main": 1,
"useip": 1,
"ip": "10.10.10.10",
"dns": "",
"port": "10050"
}
],
"groups": [
{}
],
"templates": [
{
"templateid": "12156"
}
],
"inventory_mode": 0,
"inventory": {
"type": "On Board Unit",
"tag": "test",
"type_full": "test",
"macaddress_a": "test",
"macaddress_b": "test",
"serialno_a": "test",
"serialno_b": "test"
}
},
"auth": "test-token",
"id": 1
}
What i am missing? Is there any more elegant way to create such a big json object instead of using structs?
type Groups struct {
Groupid string json:"groupid"
Groupid1 string json:"groupid"
}
groupid - Cannot be the same value for both. Change it as follows and it should work.
type Groups struct {
Groupid string json:"groupid"
Groupid1 string json:"groupid1"
}
type Groups struct {
Groupid string `json:"groupid"`
Groupid1 string `json:"groupid"`
}
groupid - Cannot be the same value for both. Change it as follows and it should work.
type Groups struct {
Groupid string `json:"groupid"`
Groupid1 string `json:"groupid1"`
}

How to deserialize JSON in swift

I want to decode a JSON file into model objects. Unfortunately it doesn't work in the right way. So I don't get errors, but the "decoding-result" don't corresponds to my expectations.
I have the following JSON file and I want to decode it in the shown structs. I have trimmed the json file. Why get I just one "slider image" instead of 5 (the property image of ImagesSlider contains an array with just the first image/element).
What am I missing?
JSON:
[{"imageSlider" : [{
"image" : [{
"imageId" : "1",
"imageName" : "germany1",
"imageBigName" : "germany1_BIG",
"imageRights" : "Peter"
}],
"image" : [{
"imageId" : "2",
"imageName" : "germany2",
"imageBigName" : "germany2_BIG",
"imageRights" : "Peter"
}],
"image" : [{
"imageId" : "3",
"imageName" : "germany3",
"imageBigName" : "germany3_BIG",
"imageRights" : "Peter"
}],
"image" : [{
"imageId" : "4",
"imageName" : "germany4",
"imageBigName" : "germany4_BIG",
"imageRights" : "Peter"
}],
"image" : [{
"imageId" : "5",
"imageName" : "germany5",
"imageBigName" : "germany5_BIG",
"imageRights" : "Peter"
}]
}]
}]
Swift:
struct CountryModel : Decodable, Equatable {
var countryName : String
var inhabitants : String
var capital : String
var currency : String
var imageName : String
var imageSlider: [ImagesSlider]
}
struct ImagesSlider : Decodable, Equatable {
var image: [Image]
}
struct Image : Decodable, Equatable {
var imageId: String
var imageName: String
var imageBigName: String
var imageRights: String
}
Decoding:
func loadData() -> [CountryModel] {
var data: Data
guard let file = Bundle.main.url(forResource: "data", withExtension: "json") else {
fatalError("Error")
}
data = try! Data(contentsOf: file)
let decoder = JSONDecoder()
return try! decoder.decode([CountryModel].self, from: data)
}
Thanks for your help...
Edit:
My question isn't solved by the linked question...
The json looks wrong, remember that you should have only one unique key per json object. Right now is:
[
{
"imageSlider": [
{
"image": [
{
"imageId": "1",
"imageName": "germany1",
"imageBigName": "germany1_BIG",
"imageRights": "Peter"
}
],
"image": [
{
"imageId": "2",
"imageName": "germany2",
"imageBigName": "germany2_BIG",
"imageRights": "Peter"
}
]
}
]
}
]
And it should be like this:
[
{
"imageSlider": [
{
"image": [
{
"imageId": "1",
"imageName": "germany1",
"imageBigName": "germany1_BIG",
"imageRights": "Peter"
},
{
"imageId": "2",
"imageName": "germany2",
"imageBigName": "germany2_BIG",
"imageRights": "Peter"
}
]
}
]
}
]
Notice that "germany2" item is inside of the array of image.
let decoder = JSONDecoder()
let jsonData = Data(jsonString.utf8)
do {
let country = try decoder.decode([CountryModel].self, from: jsonData)
print(country[0].imageSlider[0].image.count)
} catch {
print(error.localizedDescription)
}
// Console message
2
Because your JSON contains multiple Images object with the same key! That is not valid and each one overwrites others (randomly probably). You should turn that json to array of objects:
[{
"imageSlider" : [{
"image" : [{
"imageId" : "1",
"imageName" : "germany1",
"imageBigName" : "germany1_BIG",
"imageRights" : "Peter"
}]},{
"image" : [{
"imageId" : "2",
"imageName" : "germany2",
"imageBigName" : "germany2_BIG",
"imageRights" : "Peter"
}]}
}]
}]
Also other keys of the CountryModel should be presented since all of them are non-optional.

How to create custom key in json response using golang

I get a following json response through golang.
[
{
"CreatedOn": "03-22-2015",
"JSONReceived": [
{
"EzpOrderID": "ezp_126",
"FirstName": "Kumar",
"LastName": "S",
"OrderDesc": "Sample"
}
],
"Status": "0",
"id": "80acbdad-8aae-4d6c-ac63-2a02a9db64b4"
},
{
"CreatedOn": "03-22-2015",
"JSONReceived": [
{
"EzpOrderID": "ezp_126",
"FirstName": "Vasanth",
"LastName": "K",
"OrderDesc": "Sample"
}
],
"Status": "0",
"id": "8f7f52a5-793a-45bd-a9b7-ed41495e0ee3"
}
]..
But i need to create with key in response. sample response as follows. How to achieve using golang programming.
{
"returnResponseData": [{
"CreatedOn": "03-22-2015",
"JSONReceived": [{
"EzpOrderID": "ezp_126",
"FirstName": "Kumar",
"LastName": "S",
"OrderDesc": "Sample"
}],
"Status": "0",
"id": "80acbdad-8aae-4d6c-ac63-2a02a9db64b4"
}, {
"CreatedOn": "03-22-2015",
"JSONReceived": [{
"EzpOrderID": "ezp_126",
"FirstName": "Vasanth",
"LastName": "K",
"OrderDesc": "Sample"
}],
"Status": "0",
"id": "8f7f52a5-793a-45bd-a9b7-ed41495e0ee3"
}]
}
Please help me to achieve this task using golang.
Whole Source code as follows:
func orderList(w http.ResponseWriter, request *http.Request) {
rows, err := r.Table("orders").Run(session)
if err != nil {
fmt.Println(err)
return
}
var resultSet []interface{}
err = rows.All(&resultSet)
if err != nil {
fmt.Printf("Error scanning database result: %s", err)
return
}
if origin := request.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(resultSet)
}
You have to define another type like this:
type Wrapper struct {
ReturnResponseData []interface{} `json:"returnResponseData"`
}
and then encode wrapper, containing your response set:
json.NewEncoder(w).Encode(&Wrapper{ReturnResponseData: resultSet})
Notice, that you have to use property tag to achieve the name "returnResponseData", starting of a small letter (because encoder doesn't encode private properties by default).