1

Strangely http POST/GET request in my code is returning empty JSON (for GET) or adding empty struct ( for POST) Here is snip of code

package main
import (
   "fmt"
    "net/http"
    "github.com/gin-gonic/gin"
)
type employee struct {
    id int64 `json:"id" binding:"required"`
} 
var all_employee = []employee{
    {id: 1},  
}

func getEmployees(context *gin.Context) {
    
    context.IndentedJSON(http.StatusOK, all_employee)
    return
}
func main() {
    router := gin.Default()
    router.GET("/allemployees", getEmployees)
}

Here is curl output

curl http://localhost:9099/allemployees

[ {} ]

ekchom
  • 113
  • 13

1 Answers1

1

That is happening because the field "id" is not exported.

To unmarshal a json to a field of a structure the field need to be exported.

Changing your model to:

type employee struct {
  Id int64 `json:"id" binding:"required"`
} 

Should fix the problem.

OBS: id != Id

This post have more details about it: JSON and dealing with unexported fields